Java Reference
In-Depth Information
The semicolon at the end of the do/while statement that immediately
follows the Boolean expression is easy to forget.
How many times does the following do/while loop execute?
int y = 10;
do
{
System.out.println(y);
y += 10;
}while(y <= 100);
The loop counter is y, which starts at 10 and is incremented by 10 each time
through the loop. Because it repeats until y equals 100, that is 10 times through
the loop. The output will be the multiples of 10:
10
20
30
40
50
60
70
80
90
100
Classroom Q & A
Q: Why did you use a do/while loop to display the multiples of 10? It
seems like you could have just used a while loop.
A: You're right. In fact, I think a while loop in that example would
have made the code more readable.
Q: So, are there situations where a do/while is required?
A: No. In fact, a while loop is the only repetition control structure you
would ever need in Java. If you can write something with a do/
while loop, a while loop can be written to do the same thing. The
upcoming section The for Loop shows you how to write a for loop,
and the same is also true with them. If you can perform a task with
a for loop, a while loop can be written that does the same thing.
Search WWH ::




Custom Search