This section uses the while
iteration statement introduced in Chapter 5 to formalize the elements of counter-controlled iteration:
a control variable (or loop counter),
the control variable’s initial value,
the control variable’s increment that’s applied during each iteration of the loop,
the loop-continuation condition that determines if looping should continue.
Consider the application of Fig. 6.1, which uses a loop to display the numbers from 1 through 10.
In Fig. 6.1, the elements of counter-controlled iteration are defined in lines 9, 11 and 14. Line 9 declares the control variable (counter
) as an int
, reserves space for it in memory and sets its initial value to 1
.
Line 13 displays control variable counter
’s value per iteration of the loop. Line 14 increments the control variable by 1 for each iteration of the loop. The while
’s loop-continuation condition (line 11) tests whether the value of the control variable is less than or equal to 10
(the final value for which the condition is true
). The program performs the while
’s body even when the control variable is 10
. The loop terminates when the control variable exceeds 10
(that is, when counter
becomes 11
).
Floating-point values are approximate, so controlling counting loops with floating-point variables of types float
or double
can result in imprecise counter values and inaccurate tests for termination. Use integer values to control counting loops.