Information Technology Reference
In-Depth Information
The for Loop
The
for
loop construct executes the body of the loop, as long as the test expression returns
true
when it is evaluated at the top of the loop. The syntax of the
for
loop is shown here and illus-
trated in Figure 9-8.
At the beginning of the
for
loop,
Initializer
is executed once.
TestExpr
is then evaluated.
f t returns
true
,
Statement
is executed, followed by
Iterator
.
Control then returns to the top of the loop, and
TestExpr
is evaluated again.
As long as
TestExpr
returns
true
,
Statement
, followed by
Iterator
, will be executed.
As soon as
TestExpr
returns
false
, execution continues at the statement following
Statement
.
Separated by semicolons
↓
↓
for(
Initializer
;
TestExpr
;
Iterator
)
Statement
Initializer
,
TestExpr
, and
Iterator
are all optional. Their positions can be left blank.
The semicolons are required.
f the
TestExpr
position is left blank, the test is
assumed to return
true
. Therefore, there
must be some other method of exiting the statement if the program is to avoid going into
an infinite loop.
Figure 9-8.
The for loop