Java Reference
In-Depth Information
Perform initialization once
No
Yes
Is the test true?
Execute the
controlled statement(s)
Perform the update
Execute statement
after for loop
Figure 2.1
Flow of for loop
If the continuation test evaluates to true , it executes the controlled statements once
and executes the update part. Then it performs the test again. If it again evaluates to
true , it executes the statements again and executes the update again. Notice that the
update is performed after the controlled statements are executed. When the test evalu-
ates to false , Java is done executing the loop and moves on to whatever statement
comes after the loop.
The for loop is the first example of a control structure that we will study.
Control Structure
A syntactic structure that controls other statements.
You should be careful to use indentation to indicate controlled statements. In the
case of the for loop, all of the statements in the body of the loop are indented as a
way to indicate that they are “inside” the loop.
Tracing for Loops
Let's examine the for loop of the WriteSquares2 program in detail:
for (int i = 1; i <= 5; i++) {
System.out.println(i + " squared = " + (i * i));
}
 
 
Search WWH ::




Custom Search