5.2 Essentials of Counter-Controlled Iteration

This section uses the while iteration statement introduced in Chapter 4 to formalize the elements of counter-controlled iteration:

  1. a control variable (or loop counter)

  2. the control variable’s initial value

  3. the control variable’s increment that’s applied during each iteration of the loop

  4. the loop-continuation condition that determines if looping should continue.

Consider the application of Fig. 5.1, which uses a loop to display the numbers from 1 through 10.

Fig. 5.1 Counter-controlled iteration with the while iteration statement.

Alternate View

 1   // Fig. 5.1: WhileCounter.cpp
 2   // Counter-controlled iteration with the while iteration statement.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main() {
 7      unsigned int counter{1}; // declare and initialize control variable
 8
 9      while (counter <= 10) { // loop-continuation condition
10         cout << counter << " ";
11         ++counter; // increment control variable
12      }
13
14     cout << endl;
15     }

1 2 3 4 5 6 7 8 9 10

In Fig. 5.1, the elements of counter-controlled iteration are defined in lines 7, 9 and 11. Line 7 declares the control variable (counter) as an unsigned int, reserves space for it in memory and sets its initial value to 1. Declarations that require initialization are executable statements. In C++, it’s more precise to call a variable declaration that also reserves memory a definition. Because definitions are declarations, too, we’ll use the term “declaration” except when the distinction is important.

Line 10 displays control variable counter’s value once per iteration of the loop. Line 11 increments the control variable by 1 for each iteration of the loop. The while’s loop-continuation condition (line 9) 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).

Error-Prevention Tip 5.1

Floating-point values are approximate, so controlling counting loops with floating-point variables can result in imprecise counter values and inaccurate tests for termination. Control counting loops with integer values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset