Skip to content

Do While Loop

The do while loop is a post-test loop, meaning it starts with a statement to be repeated, then a condition. As the condition is after the body of the loop, the code inside the loop will be repeated one or more times depending on the value of the condition. This is visualised in the diagram below. These loops are rarely used but are useful to know about.

The Post-Test Loop runs the loops body, then checks the condition

Do While — when, why, and how

In most cases you will use a pre-test loop. The do while is provided for situations where it really makes more sense to check the condition after the loop. You can usually achieve the same thing with a regular while loop with a carefully designed condition, but sometimes a do while loop is still a better choice.

Do while will perform the following actions:

  1. Execute the body of the loop.
  2. Evaluate the condition. If the condition is true, jump back to the start of the loop. If the condition false, continue with the code after the loop.

Notice that this ordering of actions means a do while loop will always run the body of the loop once.

As with the pre-test loop, the do while loop controls the flow of instructions to the CPU. The only different between the two is the location of the condition. So, with the do while loop, a repetition of the loop’s body means “rewinding” through the sequence back to the start of the loop, as shown in the image below.

A do while loop is still seen as a sequence of instructions to the CPU

In C

This loop starts with the keyword do, followed by a statement to be repeated. As with the while loop, this will almost always be a compound statement. Following the statement there is the keyword while, followed by a condition in parentheses.

How does do while work?

The following code demonstrates the use of a do while loop to repeat some code. The body of the loop will run once, and at the end check if again is “y” or “Y”. When it is, the computer will move back to the start of the statement after the do keyword, repeating that code, and checking the condition again. This will repeat until the condition is false (i.e., the user enters “y” or “Y”).

using static System.Console;
string again;
do
{
WriteLine("Hello");
Write("Again: ");
again = ReadLine();
} while (again == "y" || again == "Y");

Use the following images to see how this works.

Notice how do marks the start of the statements to repeat, and while evaluates the condition and jumps back as needed. As with the while loop, the do while loop’s condition is only checked when the computer is at that location in the code. This means we can still think about the do while loop as part of a sequence — although it can cause some code to be repeated, overall it still has just one entry and exit point.