do...while

Summary

A do...while loop is used to repeatedly execute code as long as a given condition is true. The condition is evaluated after the statement so, in a do...while loop, the statement is always executed at least once.

Syntax

do
    statement;
while (condition);

Parameters

statement
The statement to execute. In order to execute a group of statements, use a block.
condition
A valid expression that must be true for the do...while loop's statement to be executed.

Description

The do...while loop will repeatedly execute its statement for as long as its condition evaluates to true.

The statement is executed and then the condition is checked. If the condition is true, the process repeats.

1
2
3
4
int i = 0;
do {
    ++i;
} while (i < 5);

In the above code, the i variable is incremented as long as it remains below 5. Therefore, at the end of the do...while loop, the value is 5.

Differences to while Loop

The difference between a regular while loop and the do...while loop is that the while loop will check the condition first and then evaluate the statement. On the other hand, a do...while loop will evaluate the statement first and then check the condition. This guarantees that the statement will always execute at least once in a do...while loop.

See Also

Share

HTML | BBCode | Direct Link