5.2. Essentials of Counter-Controlled Repetition
This section uses the while repetition statement introduced in Chapter 4 to formalize the elements required to perform counter-controlled repetition. Counter-controlled repetition requires
Consider the simple program in Fig. 5.1, which prints the numbers from 1 to 10. The declaration at line 9 names the control variable (counter), declares it to be an integer, reserves space for it in memory and sets it to an initial value of 1. Declarations that require initialization are, in effect, executable statements. In C++, it is more precise to call a declaration that also reserves memoryas the preceding declaration doesa definition. Because definitions are declarations, too, we will use the term "declaration" except when the distinction is important.
Figure 5.1. Counter-controlled repetition.
The declaration and initialization of counter (line 9) also could have been accomplished with the statements
int counter; // declare control variable counter = 1; // initialize control variable to 1
We use both methods of initializing variables.
Line 14 increments the loop counter by 1 each time the loop's body is performed. The loop-continuation condition (line 11) in the while statement determines whether the value of the control variable is less than or equal to 10 (the final value for which the condition is TRue). Note that the body of this while executes even when the control variable is 10. The loop terminates when the control variable is greater than 10 (i.e., when counter becomes 11).
Figure 5.1 can be made more concise by initializing counter to 0 and by replacing the while statement with
while ( ++counter <= 10 ) // loop-continuation condition cout << counter << " ";
This code saves a statement, because the incrementing is done directly in the while condition before the condition is tested. Also, the code eliminates the braces around the body of the while, because the while now contains only one statement. Coding in such a condensed fashion takes some practice and can lead to programs that are more difficult to read, debug, modify and maintain.
Common Programming Error 5.1
Error-Prevention Tip 5.1
Good Programming Practice 5.1
Good Programming Practice 5.2
Good Programming Practice 5.3