Java Reference
In-Depth Information
EXAMPLE 5-9
The following
for
loop prints the first 10 non-negative integers: (Assume that
i
is an
int
variable.)
for
(i = 0; i < 10; i++)
System.out.print(i + " " );
System.out.println();
The
initial expression
,
i = 0;
, initializes
i
to
0
. Next, the
logical expression
,
i < 10
, is evaluated. Because
0 < 10
is
true
, the print statement executes and outputs
0
.
The
update expression
,
i++
, then executes, which sets the value of
i
to
1
. Once
again, the
logical expression
is evaluated, which is still
true
, and so on. When
i
becomes
10
, the
logical expression
evaluates to
false
, the
for
loop terminates, and
the statement following the
for
loop executes.
The following examples further illustrate how a
for
loop executes.
EXAMPLE 5-10
1. The following
for
loop outputs the word
Hello
and a star (on separate
lines) five times:
for
(i = 1; i <= 5; i++)
{
System.out.println("Hello");
System.out.println("*");
}
2. Now consider the following
for
loop:
for
(i = 1; i <= 5; i++)
System.out.println("Hello");
System.out.println("*");
This loop outputs the word
Hello
five times and the star only once. In this case, the
for
loop controls only the first output statement because the two output statements are not
made into a compound statement using braces. Therefore, the first output statement
executes five times because the
for
loop executes five times. After the
for
loop executes,
the second output statement executes only once.
Search WWH ::
Custom Search