Java Reference
In-Depth Information
EXAMPLE 5-11
The following
for
loop executes five empty statements:
for
(i = 0; i < 5; i++);
//Line 1
System.out.println("*");
//Line 2
The semicolon at the end of the
for
statement (before the output statement in Line 2)
terminates the
for
loop. The action of this
for
loop is empty. The statement in Line 2
outputs a star.
The preceding examples show that care is required to get a
for
loop to perform the
desired action.
Some additional comments on
for
loops follow:
If the
logical expression
is initially
false
, the loop body does not
execute.
The update expression, when executed, should change the value of the loop
control variable, which eventually sets the value of the loop condition to
false
.The
for
loop executes indefinitely if the loop condition is always
true
.
5
If you put a semicolon at the end of a
for
statement (just before the body
of the loop), the action of the
for
loop is empty.
In a
for
statement, if the
logical expression
is omitted, it is assumed
to be
true
.
In a
for
statement, you can omit all three statements—
initial
expression
,
logical expression
, and
update expression
. The
following is a legal
for
loop:
for
(;;)
System.out.println("Hello");
This is an infinite
for
loop, continuously printing the world
Hello
.
More examples of
for
loops follow.
EXAMPLE 5-12
1. You can count backward using a
for
loop if the
for
loop control
expressions are set correctly. For example, consider the following
for
loop:
for
(i = 10; i >= 1; i--)
System.out.print(i + " ");
System.out.println();
Search WWH ::
Custom Search