Information Technology Reference
In-Depth Information
Figure 9-8 illustrates the flow of control through the
for
statement. You should also know
the following about its components:
Initializer
is executed only once, before any other part of the
for
construct. It is usu-
ally used to declare and initialize local values to be used in the loop.
TestExpr
is evaluated to determine whether
Statement
should be executed or skipped. It
must evaluate to a value of type
bool
.
Iterator
is executed immediately after
Statement
, and before returning to the top of the
loop to
TestExpr
.
For example, in the following code:
Before anything else, the initializer (
int i=0
) defines a variable called
i
, and initializes its
value to
0
.
The cond ion
i<3
) is then evaluated. If it is
true
, then the body of the loop is executed.
At the bottom of the loop, after all the loop statements have been executed, the iterator
statement is executed—in this case incrementing the value of
i
.
// The body of this for loop is executed three times.
for( int i=0 ; i<3 ; i++ )
Console.WriteLine("Inside loop. i: {0}", i);
Console.WriteLine("Out of Loop");
The output from this code is the following:
Inside loop. i: 0
Inside loop. i: 1
Inside loop. i: 2
Out of Loop