Java Reference
In-Depth Information
Table 2.6
Trace of for (int i = 1; i <= 5; i++)
Step
Code
Description
initialization
variable i is created and initialized to 1
int i = 1;
test
true because 1 <= 5 , so we enter the loop
i <= 5
body
execute the println with i equal to 1
{...}
update
increment i , which becomes 2
i++
test
true because 2 <= 5 , so we enter the loop
i <= 5
body
execute the println with i equal to 2
{...}
update
increment i , which becomes 3
i++
test
true because 3 <= 5 , so we enter the loop
i <= 5
body
execute the println with i equal to 3
{...}
update
increment i , which becomes 4
i++
test
true because 4 <= 5 , so we enter the loop
i <= 5
body
execute the println with i equal to 4
{...}
update
increment i , which becomes 5
i++
test
true because 5 <= 5 , so we enter the loop
i <= 5
body
execute the println with i equal to 5
{...}
update
increment i , which becomes 6
i++
test
false because 6 > 5 , so we are finished
i <= 5
In this loop, the initialization ( int i = 1 ) declares an integer variable i that is
initialized to 1 . The continuation test ( i <= 5 ) indicates that we should keep execut-
ing as long as i is less than or equal to 5 . That means that once i is greater than 5 ,we
will stop executing the body of the loop. The update ( i++ ) will increment the value
of i by one each time, bringing i closer to being larger than 5 . After five executions
of the body and the accompanying five updates, i will be larger than 5 and the loop
will finish executing. Table 2.6 traces this process in detail.
Java allows great flexibility in deciding what to include in the initialization part and
the update, so we can use the for loop to solve all sorts of programming tasks. For
now, though, we will restrict ourselves to a particular kind of loop that declares and ini-
tializes a single variable that is used to control the loop. This variable is often referred
to as the control variable of the loop. In the test we compare the control variable
against some final desired value, and in the update we change the value of the control
variable, most often incrementing it by 1 . Such loops are very common in program-
ming. By convention, we often use names like i , j , and k for the control variables.
Each execution of the controlled statement of a loop is called an iteration of the
loop (as in, “The loop finished executing after four iterations”). Iteration also refers
to looping in general (as in, “I solved the problem using iteration”).
Consider another for loop:
for (int i = 100; i <= 100; i++) {
System.out.println(i + " squared = " + (i * i));
}
 
Search WWH ::




Custom Search