All three aspects of controlling the loop...
...are set up in one statement. This makes it easier to check if you have done things correctly.
But there is another (less important) aspect of loop control: declaring the loop control variable. For example, here is a counting loop:
int count; . . . . . . for ( count = 0; count < 10; count++ ) System.out.print( count + " " );
The loop control variable
count is declared somewhere else in
the program (possible many statements away from the
This violates the idea that all the loop control is in one statement.
It would be nice if the declaration of
count were part of the
this can be done, as in the following:
for ( int count = 0; count < 10; count++ ) System.out.print( count + " " );
In this example, the declaration of
count and its initialization
have been combined.
there is an important difference between this program fragment and the previous one:
Scope Rule: a variable declared in a
forstatement can only be used in that statement and the body of the loop.
The following is NOT correct:
for ( int count = 0; count < 10; count++ ) System.out.print( count + " " ); // NOT part of the loop body System.out.println( "\nAfter the loop count is: " + count );
println() statement is not part of the loop body,
it cannot use
The compiler complained that it "cannot resolve the symbol" when it sees the
count that is outside of the scope of the declaration.
This can be a baffling error message if you forget the scope rule.