for Repetition Statement
Section 6.2 presented the essentials of counter-controlled repetition. The while statement can be used to implement any counter-controlled loop. C# also provides the for repetition statement, which specifies the elements of counter-controlled-repetition in a single line of code. Figure 6.2 reimplements the application in Fig. 6.1 using the for statement.
Figure 6.2. Counter-controlled repetition with the for repetition statement.
1 // Fig. 6.2: ForCounter.cs 2 // Counter-controlled repetition with the for repetition statement. 3 using System; 4 5 public class ForCounter 6 { 7 public static void Main( string[] args ) 8 { 9 // for statement header includes initialization, 10 // loop-continuation condition and increment 11 for ( int counter = 1; counter <= 10; counter++ ) 12 Console.Write( "{0} ", counter ); 13 14 Console.WriteLine(); // output a newline 15 } // end Main 16 } // end class ForCounter
|
The application's Main method operates as follows: when the for statement (lines 1112) begins executing, control variable counter is declared and initialized to 1. (Recall from Section 6.2 that the first two elements of counter-controlled repetition are the control variable and its initial value.) Next, the application checks the loop-continuation condition, counter <= 10, which is between the two required semicolons. Because the initial value of counter is 1, the condition initially is true. Therefore, the body statement (line 12) displays control variable counter's value, which is 1. After executing the loop's body, the application increments counter in the expression counter++, which appears to the right of the second semicolon. Then the loop-continuation test is performed again to determine whether the application should continue with the next iteration of the loop. At this point, the control variable value is 2, so the condition is still true (the final value is not exceeded)and the application performs the body statement again (i.e., the next iteration of the loop). This process continues until the numbers 1 through 10 have been displayed and the counter's value becomes 11, causing the loop-continuation test to fail and repetition to terminate (after 10 repetitions of the loop body at line 12). Then the application performs the first statement after the forin this case, line 14.
Note that Fig. 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 timesa common logic error called an off-by-one error.
|
Figure 6.3 takes a closer look at the for statement in Fig. 6.2. The for's first line (including the keyword for and everything in parentheses after for)line 11 in Fig. 6.2is sometimes called the for statement header, or simply the for header. Note that the for header "does it all"it specifies each of the items needed for counter-controlled repetition with a control variable. If there is more than one statement in the body of the for, braces are required to define the body of the loop.
Figure 6.3. for statement header components.
The general format of the for statement is
for ( initialization; loopContinuationCondition; increment ) statement
where the initialization expression names the loop's control variable and provides its initial value, the loopContinuationCondition is the condition that 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 false. The two semicolons in the for header are required. Note that we don't include a semicolon after statement because the semicolon is already assumed to be included in the notion of a statement.
|
In most cases, the for statement can be represented with an equivalent while statement as follows:
initialization; while ( loopContinuationCondition ) { statement increment; }
In Section 6.7, we discuss a case in which a for statement cannot be represented with an equivalent while statement.
Typically, for statements are used for counter-controlled repetition, and while statements are used for sentinel-controlled repetition. However, while and for can each be used for either repetition type.
If the initialization expression in the for 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 statementit will not exist outside the for statement. 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 application. 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 method. Scope is discussed in detail in Chapter 7, Methods: A Deeper Look.
|
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 can omit the initialization expression if the application initializes the control variable before the loopin this case, the scope of the control variable will not be limited to the loop. You can omit the increment expression if the application 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 stand-alone statement at the end of the for's body. Therefore, the expressions
counter = counter + 1 counter += 1 ++counter counter++
are equivalent increment expressions in a for statement. Many programmers prefer counter++ because it is concise and because a for loop evaluates its increment expression after its body executesso 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.
|
|
|
|
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, then the statement
for ( int j = x; j <= 4 * x * y; j += y / x )
is equivalent to the statement
for ( int j = 2; j <= 80; j += 5 )
The increment of a for statement may also be negative, in which case it is a decrement, and the loop counts downward.
If the loop-continuation condition is initially false, the application does not execute the for statement's body. Instead, execution proceeds with the statement following the for.
Applications 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 repetition without being mentioned in the body of the for.
|
The for statement's UML activity diagram is similar to that of the while statement (Fig. 5.4). Figure 6.4 shows the activity diagram of the for 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.
Figure 6.4. UML activity diagram for the for statement in Fig. 6.2.
Examples Using the for Statement
|