- 4.1 Introduction
- 4.2 Essentials of Counter-Controlled Iteration
- 4.3 for Iteration Statement
- 4.4 Examples Using the for Statement
- 4.5 Application: Summing Even Integers
- 4.6 Application: Compound-Interest Calculations
- 4.7 do... while Iteration Statement
- 4.8 switch Multiple-Selection Statement
- 4.9 C++17 Selection Statements with Initializers
- 4.10 break and continue Statements
- 4.11 Logical Operators
- 4.12 Confusing the Equality (==) and Assignment (=) Operators
- 4.13 Objects-Natural Case Study: Using the miniz-cpp Library to Write and Read ZIP files
- 4.14 C++20 Text Formatting with Field Widths and Precisions
- 4.15 Wrap-Up
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:
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 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.