Java Reference
In-Depth Information
The output is:
10 9 8 7 6 5 4 3 2 1
In this
for
loop, the variable
i
is initialized to
10
. After each iteration of the
loop,
i
is decremented by
1
. The loop continues to execute as long as
i >= 1
.
2. You can increment (or decrement) the loop control variable by any fixed
number (or modify it in any way you please). In the following
for
loop, the
variable is initialized to
0
; at the end of the
for
loop,
i
is incremented by
2
.
This
for
loop outputs
10
even integers
0
through
18
:
for
(i = 0; i < 20; i = i + 2)
System.out.print(i + " ");
System.out.println();
EXAMPLE 5-13
Consider the following examples, where
i
is an
int
variable.
1.
for
(i = 10; i <= 9; i++)
System.out.print(i + " ");
System.out.println();
In this
for
loop, the initial expression sets
i
to
10
. Because initially the
logical expression (
i <= 9
)is
false
,thebodyofthe
for
loop does not
execute.
2.
for
(i = 9; i >= 10; i--)
System.out.print(i + " ");
System.out.println();
In this
for
loop, the initial expression sets
i
to
9
. Because initially the logical
expression (
i >= 10
)is
false
, the body of the
for
loop does not execute.
3.
for
(i = 10; i <= 10; i++)
//Line 1
System.out.print(i + " ");
//Line 2
System.out.println();
//Line 3
In this
for
loop, the output statement in Line 2 executes once.
4.
for
(i = 1; i <= 10; i++);
System.out.print(i + " ");
System.out.println();
Search WWH ::
Custom Search