Java Reference
In-Depth Information
The output of this code is:
0 5 10 15 20
After the value
20
is output, the statement:
i = i + 5;
changes the value of
i
to
25
,so
i <= 20
becomes
false
, which halts the loop.
Because the
while
or
for
loops both have entry conditions, these loops might never
activate. The
do
...
while
loop, on the other hand, has an exit condition; therefore, the
body of the
do
...
while
loop always executes at least once.
In a
while
or
for
loop, the loop condition is evaluated before executing the body of the
loop. Therefore,
while
and
for
loops are called pretest loops. On the other hand, the
loop condition in a
do
...
while
loop is evaluated after executing the body of the loop.
Therefore,
do
...
while
loops are called post-test loops.
EXAMPLE 5-17
Consider the following two loops:
a.
i = 11;
while
(i <= 10)
{
System.out.print(i + " ");
i = i + 5;
}
System.out.println();
b.
i = 11;
do
{
System.out.print(i + " ");
i = i + 5;
}
while
(i <= 10);
System.out.println();
In (a), the
while
loop produces nothing. In (b), the
do
...
while
loop outputs the
number
11
and also changes the value of
i
to
16
.
A
do
...
while
loop can be used for input validation. Suppose that a program prompts a user
to enter a test score, which must be greater than or equal to
0
and less than or equal to
50
.If
the user enters a score less than
0
or greater than
50
, the user should be prompted to re-enter
the score. The following
do
...
while
loop can be used to accomplish this objective:
Search WWH ::
Custom Search