C++ - do while c++ - do while loop - do while loop c++

Our Guide to the C++ Do-While Loop

C++ developers must often loop over code blocks, usually provided a condition is met. But what if you need to run your code block at least once, regardless of whether a condition evaluates to true? The C++ do-while loop makes this possible.

What Is a While Loop?

The do-while is a variant of the while loop, which is just one of several types of loops in the C++ programming language. Before diving into do-while loops, let’s first look at the regular while loop.

The while loop continuously executes a block of code as long as a specified condition is true:

while (condition) {
  // code
}

We can see that this block will run only when a condition is met. Let’s look at an implementation of the while loop. Here, we print out a number as long as it’s below 5:

int i = 0;
while (i < 5) {
    cout << i << "\n";
    i++;
}

Every time we pass through the loop, we increment the number. When i reaches 4, it meets the conditional statement for the last time and the code block executes. In that code block, i is incremented to 5 and the loop terminates because i’s value no longer meets the condition.

But what if i were initiated at i = 6? We can see the loop would never run. If we did want the loop’s code block to execute at least once no matter what, we would turn to the C++ do-while loop.

What Is a Do-While Loop?

The do-while loop is a “post-test loop:” It executes the code block once, before checking if the applicable condition is true. If the condition is true, then the program will repeat the loop. If the condition proves false, the loop terminates.

do {
    // code
} while (condition);

Even though a C++ do-while loop appears structurally different compared to the while loop, the meaningful difference between the two is that with a do-while loop, the condition is at the end. The following program prints the number “6” once before the loop terminates, due to the condition evaluating to false:

int i = 6;
do {
    cout << i << "\n";
    i++;
} while (i < 5);

// output:
// 6

To better grasp the loop, let’s look at the flow in more detail. First the program executes the “do” code block even though i = 6 does not meet the testing condition. You can think of the do in the loop’s first iteration as the program demanding: “Do this no matter what!”

Then, we reach the condition, where the program says “hold on … we’ll only execute this do again if it passes our requirements.” If the condition is true, the program indeed executes the code block again. But if it’s false, the loop terminates. Now that we have a better idea of the C++ do-while loop flow, let’s look at some more examples of real-life functionality.

Examples of Do-While Loops

Let’s look at a full program for running a do-while loop. You’ll notice a few details in our code that differ from the above snippets — but these are what make it a full C++ program. We’ll add #include <iostream> so that we can interact with the console by reading from and writing to it. We’ll also use the namespace std, referring to the standard namespace, which allows us to use std‘s classes and functions without having to call std every time. In the main() function, we’ll add the logic of the program.

#include <iostream>
using namespace std;
int main()
{
    int num, product = 1;
    do {
        cout << "Enter a number: ";
        cin >> num;
        product *= num;
    } while (num != 1);
    cout << "Product is " << product;
    return 0;
}

In this example, we see how a C++ do-while loop can be used to multiply numbers to a running product. We declare two integer variables in the body of our main function:  num and product, which we initialize with a value of 1. In the do portion of our loop, we prompt the user for input by printing the text “Enter a number: ” to the console. 

We then access console input with cin — a function that reads user input — to obtain the entered number and save it as the value of num. As long as the input entered isn’t 1, the program will continue prompting for input and multiplying it to the product. Every time the loop runs, the test expression checks to see if the input is an integer other than 1. If the user enters 1, the loop will terminate.

After the loop finishes, we print the value of the product to the console. Because the main() function should return an integer value as specified by int main(), we have it return 0.

We can also have nested do-while loops in C++. Let’s take a minute to look at an example with functionality that’s similar to the previous example. In this case, we’ll calculate a sum in our outer loop and a difference in our inner loop:

#include <iostream> 
using namespace std;
int main() {
    int a = 1, sum = 0;
    do {
        int b = 3, difference = 10;
        do {
            difference -= b;
            b--;
            cout << "Difference is " << difference << "\n";
        } while (b >= 1);
        sum += a;
        a++;
        cout << "Sum is " << sum << "\n";
    } while (a <= 4);
    return 0;
}

Each time we run our outer do-while loop, we run our inner do-while loop three times. This is because b is initialized at 3 and decrements with every pass of the inner do-while until it reaches the value of 1 and terminates. The outer loop code then resumes and, in total, runs through four times from a = 1 until  a = 4.

Unlike in our previous example, we print out the sum and difference at every pass of the respective do-while loops (and not after), so that we can track these values as they change. We’ll achieve the same inner loop result every time we run the outer loop, since we reset b to 3 at the beginning of every outer loop. We’ll see a different result for sum every time we run the outer loop, because we only set a outside the outer loop, so it’s not ever reset in any looping functionality. The results are printed to the console as follows:

Difference is 7
Difference is 5
Difference is 4
Sum is 1
Difference is 7
Difference is 5
Difference is 4
Sum is 3
Difference is 7
Difference is 5
Difference is 4
Sum is 6
Difference is 7
Difference is 5
Difference is 4
Sum is 10

What would happen if we were to move the line int b = 3, difference = 10; outside of the outer loop, just under int a = 1, sum = 0;? We would have a different difference each time the inner loop were to run! We recommend trying this out for yourself in a C++ IDE and seeing what happens.

When Are Do-While Loops Useful?

Loops in general are useful when you don’t know the exact number of iterations you’ll need to achieve a terminating condition. But C++ do-while loops are most useful when the program doesn’t make any sense until the statements have run at least once. 

For example, say you want to write a loop where you’re prompting the user for input and execute some specified code depending on that input. You’d want this prompt to execute at least once and then ask the user whether they want to continue.

Do-While Loop Alternative

The alternative to a do-while loop is to refactor your code block into a normal while loop and use the same functionality both before (so that the code runs at least once) and in a while loop. Let’s say we have a variable i and we initialize it at 1. We want i to be printed at least once, but that won’t happen with the following while loop:

int i = 1;
while (i > 2 && i < 5) {
  cout << i << "\n";
  i++;
}

As you can see, i = 1 doesn’t meet the given test condition, so we skip over the loop. If we wanted to print i without using a C++ do-while loop, we’d have to do something like this:

int i = 1;
cout << i << "\n";
i++;
while (i > 2 && i < 5) {
  cout << i << "\n";
  i++;
}

This involves duplicating cout << i << “\n”; and i++;. Instead, using the do keyword lets us state that this is a foot-controlled loop and eliminates the need for repetition:

int i = 1;
do {
  cout << i << "\n";
  i++;
} while (i > 2 && i < 5)

For this reason, it’s better to use the do-while loop and keep our code clean.

Become a C++ Developer

Loops in general comprise one of many tools you’ll need to become an C++ developer. 

Are you up for the challenge? 

Our expert-taught C++ Nanodegree not only covers everything you need to know about loops, but even gives you the opportunity to build your own C++ application. 

Start Learning