DEV Community

Cover image for The do-while Loop
Paul Ngugi
Paul Ngugi

Posted on

The do-while Loop

A do-while loop is the same as a while loop except that it executes the loop body first and then checks the loop continuation condition.

The do-while loop is a variation of the while loop. Its syntax is:

do {
// Loop body;
 Statement(s);
} while (loop-continuation-condition);
Enter fullscreen mode Exit fullscreen mode

Its execution flowchart is shown below.

Image description
The loop body is executed first, and then the loop-continuation-condition is evaluated. If the evaluation is true, the loop body is executed again; if it is false, the do-while loop terminates. The difference between a while loop and a do-while loop is the order in which the loop-continuation-condition is evaluated and the loop body executed. You can write a loop using either the while loop or the do-while loop. Sometimes one is a more convenient choice than the other. For example, here's a do-while loop, as shown below:

Image description

Use a do-while loop if you have statements inside the loop that must be executed at least once, as in the case of the do-while loop in the preceding TestDoWhile program. These statements must appear before the loop as well as inside it if you use a while loop.

Top comments (0)