Section 5.8 Check Point Questions7 questions
5.8.1
Do the following two loops result in the same value in sum?
(a) for (int i = 0; i < 10; ++i) { sum += i; } (b) for (int i = 0; i < 10; i++) { sum += i; }
5.8.2
What are the three parts of a for loop control? Write a for loop that prints the numbers from 1 to 100.
5.8.3
Suppose the input is 2 3 4 5 0. What is the output of the following code?
#include <iostream> using namespace std; int main() { int number, sum = 0, count; for (count = 0; count < 5; count++) { cin >> number; sum += number; } cout << "sum is " << sum << endl; cout << "count is " << count << endl; return 0; }
5.8.4
What does the following statement do?
for ( ; ; ) { // Do something }
5.8.5
If a variable is declared in a for loop control, can it be used after the loop exits?
5.8.6
Convert the following for loop statement to a while loop and to a do-while loop:
long sum = 0; for (int i = 0; i <= 1000; i++) sum = sum + i;
5.8.7
Count the number of iterations in the following loops.
(a) int count = 0; while (count < n) { count++; } (b) for (int count = 0; count <= n; count++) { } (c) int count = 5; while (count < n) { count++; } (d) int count = 5; while (count < n) { count = count + 3; }