Java Reference
In-Depth Information
The
while
and the
do
statements are good to use when you don't
initially know how many times you want to execute the loop body.
The
for statement
is another repetition statement that is particularly
well suited for executing the body of a loop a specific number of
times that can be determined before the loop is executed.
The following code prints the numbers 1 through 5 using a
for
loop, just as
we did using other loop statements in previous examples:
KEY CONCEPT
A
for
statement is usually used
when a loop will be executed a set
number of times.
for
(
int
count=1; count <= 5; count++)
System.out.println (count);
The header of a
for
loop contains three parts separated by semicolons. Before
the loop begins, the first part of the header, called the
initialization,
is executed.
The second part of the header is the boolean condition, which is evaluated
before the loop body (like the
while
loop). If true, the body of the loop is
executed, followed by the execution of the third part of the header, which is
called the
increment.
Note that the initialization part is executed only once, but
the increment part is executed after each iteration of the loop. Figure 6.2 shows
this processing.
initialization
condition
evaluated
true
false
statement
increment
FIGURE 6.2
The logic of a
for
loop
Search WWH ::
Custom Search