- 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.3 for Iteration Statement
The for iteration statement specifies the counter-controlled-iteration details in a single line of code. Figure 4.2 reimplements the application of Fig. 4.1 using a for statement.
1 // fig04_02.cpp 2 // Counter-controlled iteration with the for iteration statement. 3 #include <iostream> 4 using namespace std; 5 6 int main() { 7 // for statement header includes initialization, 8 // loop-continuation condition and increment 9 for (int counter{1}; counter <= 10; ++counter) { 10 cout << counter << " "; 11 } 12 13 cout << "\n"; 14 }
1 2 3 4 5 6 7 8 9 10
Fig. 4.2 Counter-controlled iteration with the for iteration statement.
When the for statement (lines 9–11) begins executing, the control variable counter is declared and initialized to 1. Next, the program tests the loop-continuation condition between the two required semicolons (counter <= 10). Because counter’s initial value is 1, the condition is true. So, line 10 displays counter’s value (1). After executing line 10, ++counter to the right of the second semicolon increments counter. Then the program performs the loop-continuation test again to determine whether to proceed with the loop’s next iteration. At this point, counter’s value is 2 and the condition is still true, so the program executes line 10 again. This process continues until the loop has displayed the numbers 1–10 and counter’s value becomes 11. At this point, the loop-continuation test fails, iteration terminates and the program continues with the first statement after the loop (line 13).
A Closer Look at the for Statement’s Header
The following diagram takes a closer look at the for statement in Fig. 4.2:
The first line—including the keyword for and everything in the parentheses after for (line 9 in Fig. 4.2)—is sometimes called the for statement header. The for header “does it all”—it specifies each item needed for counter-controlled iteration with a control variable.
General Format of a for Statement
The general format of the for statement is
for (initialization; loopContinuationCondition; increment) { statement }
where
initialization names the loop’s control variable and provides its initial value,
loopContinuationCondition—between the two required semicolons—determines whether the loop should continue executing, and
increment modifies the control variable’s value so that the loop-continuation condition eventually becomes false.
If the loop-continuation condition is initially false, the program does not execute the for statement’s body. Instead, execution proceeds with the statement following the for.
Scope of a for Statement’s Control Variable
If the initialization expression declares the control variable, it can be used only in that for statement—not beyond it. This restricted use is known as the variable’s scope, which defines its lifetime and where it can be used in a program. For example, a variable’s scope is from its declaration point to the right brace that closes the block. As you’ll see in Chapter 5, it’s good practice to define each variable in the smallest scope needed.
Expressions in a for Statement’s Header Are Optional
All three expressions in a for header are optional. If you omit the loopContinuationCondition, the condition is always true, creating an infinite loop. You might omit the initialization expression if the program initializes the control variable before the loop. You might omit the increment expression if the program calculates the increment in the loop’s body or if no increment is needed.
The increment expression in a for acts like a stand-alone statement at the end of the for’s body. Therefore, the increment expressions
counter = counter + 1 counter += 1 ++counter counter++
are equivalent in a for statement. In this case, the increment expression does not appear in a larger expression, so preincrementing and postincrementing have the same effect. We prefer preincrement. In Chapter 11’s operator-overloading discussion, you’ll see that preincrement can have a performance advantage.
Using a for Statement’s Control Variable in the Statement’s Body
Err Programs frequently display the control-variable value or use it in calculations in the loop body, but this use is not required. The value of the control variable can be changed in a for loop’s body, but doing so can lead to subtle errors. If a program must modify the control variable’s value in the loop’s body, prefer while to for.
UML Activity Diagram of the for Statement
Below is the UML activity diagram of the for statement in Fig. 4.2—it makes it clear that initialization occurs once, before the condition is tested the first time. Incrementing occurs after the body statement executes: