Java Reference
In-Depth Information
count = 0;
loop-
continuation-
condition?
false
false
(count < 100)?
true
true
System.out.println("Welcome to Java!");
count++;
Statement(s)
(loop body)
(a)
(b)
F
IGURE
5.1
The
while
loop repeatedly executes the statements in the loop body when the
loop-continuation-condition
evaluates to
true
.
loop-continuation-condition
is
count < 100
and the loop body contains the follow-
ing two statements:
loop-continuation-condition
int
count =
0
;
while
(count <
100
) {
System.out.printIn(
"Welcome to Java!"
);
loop body
count++;
}
In this example, you know exactly how many times the loop body needs to be executed
because the control variable
count
is used to count the number of executions. This type of
loop is known as a
counter-controlled loop.
counter-controlled loop
Note
The
loop-continuation-condition
must always appear inside the parentheses.
The braces enclosing the loop body can be omitted only if the loop body contains one
or no statement.
Here is another example to help understand how a loop works.
int
sum =
0
, i =
1
;
while
(i <
10
) {
sum = sum + i;
i++;
}
System.out.println(
"sum is "
+ sum);
// sum is 45
If
i < 10
is
true
, the program adds
i
to
sum
. Variable
i
is initially set to
1
, then is incre-
mented to
2
,
3
, and up to
10
. When
i
is
10
,
i < 10
is
false
, so the loop exits. Therefore,
the sum is
1 + 2 + 3 + ... + 9 = 45
.
What happens if the loop is mistakenly written as follows?
int
sum =
0
, i =
1
;
while
(i <
10
) {
sum = sum + i;
}
This loop is infinite, because
i
is always
1
and
i < 10
will always be
true
.
Search WWH ::
Custom Search