The do Statement

In this lesson, we introduce another statement to control a loop, the do statement.


We have seen that the logic of a for loop is identical to the logic of a while loop. Both loops can end immediately after the first test of a given Boolean expression without executing the body of the loop. This behavior is desirable for most loops, so these two statements are the ones that we usually will use for our loops.

Occasionally, however, we will know in advance that the body of a loop must execute at least once. Although we could choose either a while statement or a for statement to implement such a loop, we could also use the do statement. The do statement executes its body, which includes the update step, before evaluating a Boolean expression to decide whether to continue the iteration.

The do statement has the following form:

📝 Syntax: The do statement

while (condition); <---- The semicolon is required

Effect: First, statement—which typically is a compound statement—executes. Next, the Boolean expression condition is evaluated. If it is true, statement executes again. Otherwise, the loop ends. The figure given below illustrates the logic of a do statement.

Get hands-on with 1200+ tech skills courses.