do-while loop

Definition

A do-while loop is a while-loop that tests its condition only after executing the body.

Benefits

Sometimes we want to always execute a loop at least once, regardless of the condition. Instead of having to write the same code before the loop, we can use a do-while loop. Other times, it is simply more practical to check the condition after the body is executed.

Code

The format of a do-while loop is as follows:

do {
  //code here
}
while (expression);

Execution

The loop will be executed in the following order:
1. loop body
2. condition check
3. go to step 1

Visual do-while loop

dowhile.jpg

Example

Tips

See the tips on the loops page.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License