1. Reverse loop
Java has another kind of while
loop — the do-while
loop. It's very similar to the ordinary while
loop and also consists of only two parts: a "condition" and a "loop body". The loop body is executed over and over again as long as the condition is true
. In general, a do-while
loop looks like this:
do
statement;
while (condition);
or
do
{
block of statements
}
while (condition);
For a while
loop, the sequence of execution is: condition, loop body, condition, loop body, condition, loop body, ...
But for a do-while
loop, it is slightly different: loop body, condition, loop body, condition, loop body, ...
In fact, the only difference between a while
loop and do-while
loop is the fact that the loop body is executed at least once for a do-while
loop.
2. Benefits of using a do-while
loop
Basically, the only difference between a do-while
loop and a while
loop is that the body of a do-while
loop is executed at least once.
Generally, a do-while
loop is used when it makes no sense to check the loop condition if the loop body has not been executed. For example, if certain calculations are performed in the loop body and then used in the condition.
Example:
The program reads lines from the keyboard until the word exit
is entered
while | do while |
---|---|
|
|
The break
and continue
statements in a do-while
loop work in the same way as in a while
loop.
3. Comparing do-while
loops: Java vs Pascal
Once again, Pascal has an analogue of the do-while
loop, but it is called a repeat-until
loop. Also, it is slightly different from the do-while
loop. In a repeat-until
loop, the condition indicates when to exit the loop rather than when to continue it.
Examples:
Pascal | Java |
---|---|
|
|
Compared to Java, the way Pascal represents this is downright beautiful. We have to start with examples from Pascal, otherwise you'll laugh.
GO TO FULL VERSION