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
String s;
while (true)
{
   s = console.nextLine();
   if (s.equals("exit"))
      break;
}
String s;
do
{
   s = console.nextLine();
}
while (!s.equals("exit"));

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
Repeat
   ReadLn(s);
Until s = 'exit';
String s;
do {
   s = console.nextLine();
}
while ( !s.equals("exit") );

Compared to Java, the way Pascal represents this is downright beautiful. We have to start with examples from Pascal, otherwise you'll laugh.


8
Task
Module 1. Java Syntax,  level 8lesson 0
Locked
Multiplication table
Initialize the MULTIPLICATION_TABLE array as a new int[10][10], fill it with a multiplication table, and then display it on the console in the following form: 1 2 3 4 … 2 4 6 8 … 3 6 9 12 … 4 8 12 16 … … The numbers in each line are separated by a space.