Home > Articles

This chapter is from the book

4.2 Essentials of Counter-Controlled Iteration

This section uses the while iteration statement introduced in Chapter 3 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 Fig. 4.1, which uses a loop to display the numbers from 1 through 10.

 1   // fig04_01.cpp
 2   // Counter-controlled iteration with the while iteration statement.
 3   #include <iostream>
 4   using namespace std;

 5
 6   int main() {
 7      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 << "\n";
15   }
1 2 3 4 5 6 7 8 9 10

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

In Fig. 4.1, lines 7, 9 and 11 define the elements of counter-controlled iteration. Line 7 declares the control variable (counter) as an int, reserves space for it in memory and sets its initial value to 1. Declarations that require initialization are executable statements. Variable declarations that also reserve memory are definitions. We’ll generally use the term “declaration,” except when the distinction is important.

Line 10 displays 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 loop terminates when the control variable exceeds 10.

Floating-point values are approximate, so controlling counting loops with floatingpoint variables can result in imprecise counter values and inaccurate termination tests, which can prevent a loop from terminating. For that reason, always control counting loops with integer variables.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.