Java Reference
In-Depth Information
int
count =
5
;
while
(count < n) {
count++;
}
int
count =
5
;
while
(count < n) {
count = count +
3
;
}
(c)
(d)
You can use a
for
loop, a
while
loop, or a
do-while
loop, whichever is convenient.
Key
Point
The
while
loop and
for
loop are called
pretest loops
because the continuation condition
is checked before the loop body is executed. The
do-while
loop is called a
posttest loop
because the condition is checked after the loop body is executed. The three forms of loop
statements—
while
,
do-while
, and
for
—are expressively equivalent; that is, you can write
a loop in any of these three forms. For example, a
while
loop in (a) in the following figure
can always be converted into the
for
loop in (b).
pretest loop
posttest loop
while
(loop-continuation-condition) {
// Loop body
for
( ; loop-continuation-condition; ) {
// Loop body
Equivalent
}
}
(a)
(b)
A
for
loop in (a) in the next figure can generally be converted into the
while
loop in
(b) except in certain special cases (see Checkpoint Question 5.25 for such a case).
for
(initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
initial-action;
while
(loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
Equivalent
}
(a)
(b)
Use the loop statement that is most intuitive and comfortable for you. In general, a
for
loop may be used if the number of repetitions is known in advance, as, for example, when
you need to display a message a hundred times. A
while
loop may be used if the number of
repetitions is not fixed, as in the case of reading the numbers until the input is
0
. A
do-while
loop can be used to replace a
while
loop if the loop body has to be executed before the con-
tinuation condition is tested.
Caution
Adding a semicolon at the end of the
for
clause before the loop body is a common
mistake, as shown below in (a). In (a), the semicolon signifies the end of the loop pre-
maturely. The loop body is actually empty, as shown in (b). (a) and (b) are equivalent.
Both are incorrect.
Error
Empty body
for
(
int
i =
0
; i <
10
; i++);
{
System.out.println(
"i is "
+ i);
}
for
(
int
i =
0
; i <
10
; i++) { };
{
System.out.println(
"i is "
+ i);
}
(a)
(b)
Search WWH ::
Custom Search