for
Iteration StatementSection 6.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 elements of counter-controlled iteration in a single line of code. 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. Figure 6.2 reimplements the app in Fig. 6.1 using the for
statement.
When the for
statement (lines 11–14) begins executing, the control variable counter
is declared and initialized to 1
. (Recall from Section 6.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 required semicolons. Because counter
’s initial value is 1
, the condition is true
. So, the body statement (line 13) 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 to 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 16).
Figure 6.2 uses (in line 11) the loop-continuation condition counter <= 10
. If you incorrectly specified counter < 10
as the condition, the loop would iterate only nine times—a common logic error called an off-by-one error.
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.
Using the final value and operator Figure 6.3 takes a closer look at the The general format of the where the initialization expression names the loop’s control variable and provides its initial value, the loopContinuationCondition determines whether looping should continue and the increment modifies the control variable’s value (whether an increment or decrement), so that the loop-continuation condition eventually becomes If the initialization expression in the When a All three expressions in a are equivalent increment expressions in a There’s a slight performance advantage to using the prefix increment operator, but if you choose the postfix increment operator because it seems more natural (as in a
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 incremented (or decremented) during each iteration of the loop. In a sentinel-controlled loop, ensure that the sentinel value is eventually entered. The initialization, loop-continuation condition and increment portions of a is equivalent to the statement The increment of a Apps 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 Although the value of the control variable can be changed in the body of a Figure 6.4 shows the activity diagram of the Error-Prevention Tip 6.2
<=
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 zero-based counting in which, to count 10 times, you’d initialize counter
to zero and use the loop-continuation test counter
<
10
.6.3.1 A Closer Look at the
for
Statement’s Headerfor
statement in Fig. 6.2. The first line—including the keyword for
and everything in parentheses after for
(line 11 in Fig. 6.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.6.3.2 General Format of a
for
Statementfor
statement is
for (initialization; loopContinuationCondition; increment)
{
statement
}
false
. The two semicolons in the for
header are required. We don’t include a semicolon after statement, because the semicolon is already assumed to be included in the notion of a statement.6.3.3 Scope of a
for
Statement’s Control Variablefor
header declares the control variable (i.e., the control variable’s type is specified before the variable name, as in Fig. 6.2), the control variable can be used only in that for
statement—it will not exist outside it. This restricted use of the name of the control variable is known as the variable’s scope. The scope of a variable defines where it can be used in an app. For example, a local variable can be used only in the method that declares the variable and only from the point of declaration through the end of the block in which the variable has been declared. Scope is discussed in detail in Chapter 7, Methods: A Deeper Look. Common Programming Error 6.2
for
statement’s control variable is declared in the initialization section of a for
’s header, using the control variable after the for’
s body is a compilation error.6.3.4 Expressions in a
for
Statement’s Header Are Optionalfor
header are optional. If the loopContinuationCondition is omitted, C# assumes that it’s always true, thus creating an infinite loop. You can omit the initialization expression if the app initializes the control variable before the loop—in this case, the scope of the control variable will not be limited to the loop. You can omit the increment expression if the app calculates the increment with statements 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 expressions
counter = counter + 1
counter += 1
++counter
counter++
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 the prefix and postfix increment operators have the same effect. Performance Tip 6.1
for
header), optimizing compilers are likely to generate code that uses the more efficient form anyway. Error-Prevention Tip 6.3
6.3.5 Placing Arithmetic Expressions in a
for
Statement’s Headerfor
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, then the statement
for (int j = x; j <= 4 * x * y; j += y / x)
for (int j = 2; j <= 80; j += 5)
for
statement may also be negative, in which case it’s actually a decrement, and the loop counts downward.6.3.6 Using a
for
Statement’s Control Variable in the Statement’s Bodyfor
. Error-Prevention Tip 6.4
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
.6.3.7 UML Activity Diagram for the
for
Statementfor
statement in Fig. 6.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.