6.2. Essentials of Counter-Controlled RepetitionThis section uses the While repetition statement introduced in Chapter 5 to highlight the elements required to perform counter-controlled repetition. Counter-controlled repetition requires
The example in Fig. 6.1 uses the four elements of counter-controlled repetition to display the even integers in the range 210. The declaration in line 5 names the control variable (counter), indicates that it is of type Integer, reserves space for it in memory and sets it to an initial value of 2. Figure 6.1. Counter-controlled repetition with the While...End While statement.
Consider the While statement (lines 710). Line 8 displays the current value of counter, and line 9 increments the control variable by 2 to prepare for the next iteration (repetition) of the loop. The loop-continuation condition in the While statement (line 7) tests whether the value of the control variable is less than or equal to 10the final value for which the condition is true. The body of the While is performed even when the control variable is 10. The loop terminates when the control variable exceeds 10 (i.e., when counter becomes 12, because the loop is incrementing by 2 each time). |