5.3 for Iteration Statement

Section 5.2 presented the essentials of counter-controlled iteration. The while statement can be used to implement any counter-controlled loop. C++ also provides the for iteration statement, which specifies the counter-controlled-iteration details in a single line of code. Figure 5.2 reimplements the application of Fig. 5.1 using for.

When the for statement (lines 9–11) begins executing, the control variable counter is declared and initialized to 1. (Recall from Section 5.2 that the first two elements of counter-controlled iteration are the control variable and its initial value.) Next, the program checks the loop-continuation condition, counter <= 10, which is between the two

Fig. 5.2 Counter-controlled iteration with the for iteration statement.

Alternate View

 1   // Fig. 5.2: ForCounter.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 (unsigned int counter{1}; counter <= 10; ++counter) {
10         cout << counter << " ";
11      }
12
13      cout << endl;
14   }

1 2 3 4 5 6 7 8 9 10

required semicolons. Because counter’s initial value is 1, the condition is true. So, the body statement (line 10) displays control variable counter’s value (1). After executing the loop’s body, the program increments counter in the expression ++counter, which appears to the right of the second semicolon. Then the program performs the loop-continuation test again to determine whether the program should continue with the loop’s next iteration. At this point, counter’s value is 2, so the condition is still true (the final value of 10 is not exceeded)—thus, the program executes the body statement again. This process continues until the numbers 1–10 have been displayed and the counter’s value becomes 11. At this point, the loop-continuation test fails, iteration terminates and the program continues executing at the first statement after the for (line 13).

Figure 5.2 uses (in line 9) the loop-continuation condition counter <= 10. If you incorrectly specified counter < 10 as the condition, the loop would iterate only nine times. This is a common logic error called an off-by-one error.

Common Programming Error 5.1

Using an incorrect relational operator or an incorrect final value of a loop counter in the loop-continuation condition of an iteration statement can cause an off-by-one error.

 

Error-Prevention Tip 5.2

Using the final value and operator <= in a loop’s condition helps avoid off-by-one errors. For a loop that outputs 1 to 10, the loop-continuation condition should be counter <= 10 rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is correct). Many programmers prefer so-called zero-based counting, in which to count 10 times, counter would be initialized to zero and the loop-continuation test would be counter < 10.

 

Error-Prevention Tip 5.3

Write loop conditions carefully to prevent loop counters from overflowing.

A Closer Look at the for Statement’s Header

Figure 5.3 takes a closer look at the for statement in Fig. 5.2. The first line—including the keyword for and everything in parentheses after for (line 9 in Fig. 5.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.

Fig. 5.3 for statement header components.

General Format of a for Statement

The general format of the for statement is


for (initialization; loopContinuationCondition; increment) {
   statement
}

where the initialization expression optionally names the loop’s control variable and provides its initial value, loopContinuationCondition determines whether the loop should continue executing and increment modifies the control variable’s value, so that the loop-continuation condition eventually becomes false. The two semicolons in the for header are required. 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.

Representing a for Statement with an Equivalent while Statement

The for statement often can be represented with an equivalent while statement as follows:


initialization;

while (loopContinuationCondition) {
   statement
   increment;
}

In Section 5.10, we show a case in which a for statement cannot be represented with an equivalent while statement. Typically, for statements are used for counter-controlled iteration and while statements for sentinel-controlled iteration. However, while and for can each be used for either iteration type.

Scope of a for Statement’s Control Variable

If the initialization expression in the for header 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 where it can be used in a program. For example, a local variable can be used only in the function that declares it and only from its declaration point to the right brace which closes that block. Scope is discussed in detail in Chapter 6, Functions and an Introduction to Recursion.

Common Programming Error 5.2

When a for statement’s control variable is declared in the initialization section of the for’s header, using the control variable after the for’s body is a compilation error.

Expressions in a for Statement’s Header Are Optional

All three expressions in a for header are optional. If the loopContinuationCondition is omitted, C++ assumes that the loop-continuation condition is always true, thus 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 as if it were a standalone 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. Many programmers prefer counter++ because it’s concise and because a for loop evaluates its increment expression after its body executes, so the postfix increment form seems more natural. In this case, the variable being incremented does not appear in a larger expression, so preincrementing and postincrementing have the same effect. We prefer preincrement.

Common Programming Error 5.3

Placing a semicolon immediately to the right of the right parenthesis of a for header makes that for’s body an empty statement. This is normally a logic error.

 

Error-Prevention Tip 5.4

Infinite loops occur when the loop-continuation condition in an iteration statement never becomes false. To prevent this situation in a counter-controlled loop, ensure that the control variable is modified during each iteration of the loop so that the loop-continuation condition will eventually become false. In a sentinel-controlled loop, ensure that the sentinel value is able to be input.

Placing Arithmetic Expressions in a for Statement’s Header

The initialization, loop-continuation condition and increment portions of a for statement can contain arithmetic expressions. For example, assume that x = 2 and y = 10. If x and y are not modified in the body of the loop, the statement


for (unsigned int j = x; j <= 4 * x * y; j += y / x)

is equivalent to the statement


for (unsigned int j = 2; j <= 80; j += 5)

The increment of a for statement may also be negative, in which case it’s a decrement, and the loop counts downward.

Using a for Statement’s Control Variable in the Statement’s Body

Programs frequently display the control-variable value or use it in calculations in the loop body, but this use is not required. The control variable is commonly used to control iteration without being mentioned in the body of the for.

Error-Prevention Tip 5.5

Although the value of the control variable can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors. If a program must modify the control variable’s value in the loop’s body, use while rather than for.

UML Activity Diagram for the for Statement

The for statement’s UML activity diagram is similar to that of the while statement (Fig. 4.8). Figure 5.4 shows the activity diagram of the for statement in Fig. 5.2. The diagram makes it clear that initialization occurs only once—before the loop-continuation test is evaluated the first time—and that incrementing occurs each time through the loop after the body statement executes.

Fig. 5.4 UML activity diagram for the for statement in Fig. 5.2.

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

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