How Do-While Loops Work in Computer Programming

Posted on

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;
} 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!";

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!";
} while (x < 5)

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

Prev1 of 4Next

Leave a Reply

Your email address will not be published. Required fields are marked *