When you're learning to program, understanding the basic building blocks is key to early success. You'll pick up the difficult topics later, but if you don't understand variable types, loops, and functions, it's tough to get far.

Most new programmers learn about if-else statements, while loops, and for loops before long. But one of the loop types you might not understand is the do-while loop. Let's discuss how this loop works, when you'll want to use it, and look at a few examples.

The Basics

A do-while loop executes a block of code at least once, checks if a condition is true, then continues to run the code inside depending on the condition. Let's take a look at a simple pseudocode example (since they help you learn!):

            do {
  output "The variable x equals " + x;
  x++;
} while (x < 5);

output "The loop has ended.";

    

In this bit of code, the lines inside the do brackets always run at least once. This means that x could be any value at the start of the loop.

If x equals 1 when the loop starts, it will repeat until x does not satisfy the condition next to while. Thus, it would run a total of 5 times. When x is not less than 5, the loop ends and continues onto the code after it. This output would look as follows:

            The variable x equals 1 The variable x equals 2 The variable x equals 3 The variable x equals 4 The variable x equals 5 The loop has ended.
    

Conversely, if x was equal to 20 when this loop started, it would only run once. So you would see one output statement, x increments to 21, and the loop would end because 21 is not less than 5. Its output would be:

            The variable x equals 20 The loop has ended.

    

Contrast With While and For Loops

How does a do-while loop differ from other loops? The most important distinction is that do-while loops test a condition after executing a code block, while other loops check a condition before running the code inside.

Consider this basic pseudocode while loop for comparison:

            x = 10;

while (x < 5) {
  output "The loop has run!";
  x++;
}

    

Here, x is set to 10 and the while loop checks that x is less than 5 before it runs. Because of this, the code inside never runs. Applying the same logic to a do-while loop gives us something like this:

            x = 10;

do {
  output "The loop has run!";
  x++;
} while (x < 5)

    

This loop will output the text once, increment x, then continue on.

Note that you can re-create the do-while functionality with an extra statement in front of a while loop, like so:

            output "Hello!";
x++;
while (x < 5) {
  output "Hello!";
  x++;
}

    

However, this is clunky and there's no reason to do it when do-while loops exist.

For Loops

Do-while loops have a similar distinction with for loops. A for loop defines a variable, specifies how long the loop should be run, and sets a behavior for the end of each iteration.

Here's a simple for loop for comparison:

            for (int i = 0; i < 5; i++) {
  output "The loop has run " + i + " times.";
}

    

This highlights a good contrast between do-while and for loops -- you know exactly how many times a for loop will run because you set up the conditions at the start. If you modify the above code into a do-while loop like this:

            do {
  output "The loop has run " + i + " times.";
  i++;
} while (i < 5);

    

You could end up with an issue when the loop runs. If you didn't initialize i somewhere else, you don't know what its value will be when the do portion runs -- and it will run at least once. If i was 500 when this loop ran, the output here would be inaccurate.

In summary:

  • A do-while loop is useful when you want to execute a command at least once, and continually until a condition is false.
  • A while loop lets you repeat a block of code as long as a condition is true, and stop as soon as the condition is no longer true.
  • A for loop lets you specify exactly how many times the loop should run by setting your own parameters.

Leaving a Do-While Loop

Of course, you must have an exit condition for do-while loops just like any other. If not, you could end up with an infinite loop. Consider the following snippet:

            x = 5;

do { 
  output "This never ends!";
} while (x < 10);

    

If you don't increment x anywhere else in the code, then this loop will run forever. Now, sometimes infinite loops are useful because the programmer sets up code to break out of the loop elsewhere. But more often than not, novice coders run into infinite loops by accident.

Here's an example of a suitable infinite loop. Let's say you're designing a game where the user rolls a die and must get a 6 to leave the home base. You want to continue to roll the die until it lands on 6, and you obviously have to roll at least once. Thus, you could use this code:

            do {
  int roll = random(1, 2, 3, 4, 5, 6);
  if (roll == 6)
    break;
} while (true);

    

The while (true) condition means that this loop will run forever, which we want because the user must roll until he gets a 6. Without the break statement, it would get stuck. But once the user rolls a 6, the if statement becomes true, and the sequence breaks out of the loop and moves onto what's after.

You don't have to use a break statement if you don't want to. In fact, it's probably better to avoid break statements if you can. They make your code harder to maintain, and ending on a condition is easier to keep track of. Thus, the modified code below achieves the same purpose:

            do {
  int roll = random(1, 2, 3, 4, 5, 6);
} while (roll != 6);

    

A Bad Infinite Loop

An infinite loop that you have a plan for exiting is fine. But sometimes you'll accidentally create an infinite loop, like in the example below:

            int x = 7;

do {
  x = 1;
  x = x + 2;
  output "x equals " + x;
} while (x < 10);

    

This might look like it increments x by 2 every loop and repeats until x is not less than 10, but look closer. Because the loop sets x equal to 1 every time it runs, this is an infinite loop. Notice that x = 1 and x = x + 2 means that x is always 3 at the end of the block no matter how many times this runs, meaning x is never less than 10.

Watch for statements inside your loop that unintentionally change a variable every time it runs to avoid situations like this.

Real-World Examples

We've discussed some hypothetical examples above, but let's take a quick look at a few useful real-world examples of do-while loops.

If you were creating a loop to read data from a file until it hit the end, you would use a do-while loop. Obviously you need to grab at least one character if you're planning to read from a file, so you could use a do-while loop like this (thanks to Stack Exchange user Steven Burnap for this example):

            do {
  result = readData(buffer);
} while (result != EOF);

    

Without a do-while, you'd have to use a slightly uglier solution:

            while (true) {
  result = readData(buffer);
  if (result == EOF)
    break;
}

    

Another example involves grabbing input from a user. Let's say you're writing a program that asks the user to enter a positive number. Using a do-while, you could make sure that their input is appropriate:

            do {
  output "Please enter a positive number:";
  int input = getInput();
} while (input < 0);

    

With this loop, the user sees the prompt to enter a number and enters a value once. If they input a negative number, the loop runs again and they're prompted to enter a positive number until they comply. Other loops simply don't make sense for this type of action.

Ready to Use Do-While Loops?

We've taken a survey of do-while loops, including their basic principles, how to best use them, and how they compare to other loops. If you don't remember anything else from this article, know that do-while loops are for when you need to run something at least once, but don't know the number of times you'll need it before initiating the loop.

Think about situations like this in your programs, and you'll easily find places where do-while loops fit. Nearly all the best beginner languages support do-while loops, so you should have no trouble implementing them.

If you're learning the basics, make sure you review our top tricks for mastering a new programming language.

What other situations can you think of where a do-while makes sense? Discuss and let us know if you're using do-while loops in your programs in the comment section!

Image Credit: Aaban via Shutterstock.com