Like other loops, the do-while loop in C++ is used to loop through a code until the given condition is satisfied. It means that the loop will only terminate if it evaluates the specified condition to be false. This can come in handy when you want to run a piece of code multiple times. For instance, if you’re going to print a statement a hundred times, then instead of writing the print statement numerous times, you can simply write the statement once and use the ‘do while’ loop in C++ to loop through the statement a hundred times.

Syntax of the Do While Loop in C++

The basic syntax of the do-while loop in C++ is:

do

{

//body

update_expression;

}

while(test expression);

In the syntax mentioned above, the different parts of the do-while loop are:

  1. Update Expression: Once you execute the loop’s body, this expression increases or decreases the loop variable by the specified value. It does this so that the condition evaluates to be false at one point in time, according to the requirement.
  2. Test Expression: It tests this expression while entering the loop. If the expression evaluates to be true, the program will enter the loop. On the other hand, if the condition evaluates to be false, the program will exit the loop.

How Does a C++ Do While Loop Work?

The flow of a do while loop execution in C++ is as follows:

  1. The control of the flow enters the do-while loop
  2. Statements inside the loop body are executed
  3. The loop variable is updated according to the value in the loop body
  4. The test expression gets evaluated
    1. If the test evaluates to true, the flow goes to step 5
    2. If the test evaluates to false, the flow exits the loop, and statements after the loop are executed
  5. The flow goes back to the second step to run the loop body again

You can demonstrate the steps mentioned above using the following flowchart diagram.

C_Plus_Plus_Do_While_Loop_1.

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

Examples of a Do While Loop C++

Now that you know the flow and working of a do while loop in C++, look at some scenarios and examples where you can use it.

Example: Displaying Numbers 1 to 10 Using Do While Loop in C++

#include <iostream>

using namespace std;

int main(){

    int x = 1; 

    // do...while loop to print 1 to 10

    do{

        cout << x << " ";

        ++x;

    }

    while (x <= 10);    

    return 0;

}

Output:

C_Plus_Plus_Do_While_Loop_2.

In the above code, you have initialized integer x = 1 and put the condition as (x<=10). When the flow enters the loop, it displays the integer value and increments it until the value reaches 11. When the value becomes 11, the condition is not met, and the flow exits the do while loop.

Example: Adding Positive Numbers Entered by the User

#include <iostream>

using namespace std;

int main(){

    int num = 0;

    int sum = 0;

    do{

        sum += num;

        // taking the input

        cout << "Enter a number to add: ";

        cin >> num;

    }

    while (num > 0);   

    // displaying the sum

    cout << "\nThe sum of the numbers is " << sum << endl;    

    return 0;

}

Output:

C_Plus_Plus_Do_While_Loop_3

In the above code, the flow enters the loop where the initial values of sum and num, which is 0 for both, are added. Later it shows a statement using cout to ask the user to enter a number. Once you enter the number, the flow passes to the while statement, where it checks the condition. Since the condition is num > 0, the loop will continue until the user enters 0 or any negative number.

What is an Infinite Do While Loop in C++?

An infinite do while loop in C++ is a scenario where the loop’s condition always evaluates to be true. In such a situation, the loop will continue to run infinite times until the memory is full. An infinite do-while loop can be achieved in two different ways: by setting the condition statement as true (while(true)) or by not adding the increment/decrement statement in the body. Here’s how to write an infinite do while loop in C++ using both ways.

Setting Condition as True

#include<iostream>  

using namespace std;  

int main(){ 

      do{    

            cout<<"This is an infinite do-while Loop example\n";    

        } while(true);     

}  

Output:

C_Plus_Plus_Do_While_Loop_4

Eliminating Increment/Decrement Statement

#include<iostream>  

using namespace std;  

int main(){

    int i=1;

    do{    

            cout<<"This is an infinite do-while Loop example\n";    

    } while(i==1);     

}  

Output:

C_Plus_Plus_Do_While_Loop_5.

What is a Nested Do-While Loop in C++?

A nested do-while loop in C++ is a do-while loop inside another do-while loop. The syntax of a nested do-while loop is as follows:

do{

  statements;

  do{

    statements;

  }while(condition);

  statements;

}while(condition);

In the above syntax, the first do statements represent the outer loop, and the second denotes the inner loop. On the other hand, the first while statement represents the inner loop, and the second indicates the outer loop.

How Does a Nested Do While Loop in C++ Work?

The flow of a nested do while loop is as follows:

Step 1: The flow enters the outer loop, and it executes once it

Step 2: After completing the statements of the outer loop, the flow enters the inner loop

Step 3: Statements of the inner loop are executed, and it evaluates its while condition

Step 4: It entirely executes the inner loop until the while condition becomes false

Step 5: While the condition of the outer loop is evaluated,

  • If the condition is true, the flow goes back to step 2
  • If the condition is false, the flow exits the nested do while loop

Example of a Nested Do While Loop in C++

Now, explore this simple example of a nested do while loop, where you will increase and print values through both do-while loops until the value for both is less than or equal to 3.

#include <iostream>  

using namespace std;

int main(){

    int x = 1;    

    do{    

        int y = 1;          

        do{    

            cout<<x<<" "<<y<<"\n";        

            y++;    

        } while (y <= 3) ;    

        x++;    

    } while (x <= 3) ;     

}

Output:

C_Plus_Plus_Do_While_Loop_6

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

What is the Difference Between While Loop Vs. Do While Loop in C++?

There is only one significant difference between the while and do while loop in C++. While using a while loop, you check the condition first, and only then the flow enters the loop. On the other hand, it executes the body once before checking the condition when using the do-while loop. This means that you can use a do while loop in situations where the number of iterations is not fixed, but you want the body to be executed only once. Now, look at the examples of both while and do while loop to see the difference between the two.

Using While Loop

#include <iostream>

using namespace std;

int main(){

// Initialization

int i = 2;

cout << "Now the flow enters the loop\n";

while(i<=1){

// body

cout << "Hello World!\n";

i++;

}

return 0;

}

Output:

C_Plus_Plus_Do_While_Loop_7

As you can see in the above output, only the cout statement outside the loop body is executed. This is because the loop body will not execute as you have initialized the value of i to be 2, which will make the condition false.

Using Do While Loop

#include <iostream>

using namespace std;

int main(){

// Initialization

int i = 2;

cout << "Now the flow enters the loop\n";

do{

// body

cout << "Hello World!\n";

i++;

}while(i<=1);

return 0;

}

Output:

C_Plus_Plus_Do_While_Loop_8

As you can see, this time, both the cout statements are executed as the do while loop body runs at least once before checking the condition. Hence, the “Hello World!” is printed once, and later, when the loop goes to check the condition, it becomes false, and the do-while loop is terminated.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

In this article, you have learned all about the do while loop in C++. You can use it to run a piece of code multiple times until the given condition is satisfied. The C++ do while loop is a fundamental concept of this programming language. If you want to learn more about fundamental concepts, refer to Simplilearn's C++ Tutorial for Beginners. The tutorial covers all the core concepts that are essential to grasp hands-on C++ Programming.

If you are familiar with the basics, you can also refer to our SkillUp programs to enhance your coding skills and understanding. Further, you can also opt for our Full-Stack Web Development Course. The course comes with hours of applied training for multiple programming languages used for web development. It also provides you with a certificate upon completion of the course. To put it simply, the course is well adept to help you excel in the Web Development field.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, ASAP!