C++ Do While Loop - C++ Programming Tutorial
C++ Course / Object-Oriented Programming / C++ Do While Loop

C++ Do While Loop

BLUF: Mastering C++ Do While Loop is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Do While Loop

C++ is renowned for its efficiency. Learn how C++ Do While Loop enables low-level control and high-performance computing in the tutorial below.

In C++, the do-while loop serves as an iteration structure similar to the while loop. It operates as an exit-controlled loop, implying that the condition is assessed after executing the loop body. This loop guarantees that the output is displayed at least once prior to evaluating the condition. The do-while loop in C++ finds application in repeating a specific section of the program multiple times.

It varies from the while loop in that it is exit-controlled and executes the loop's body at least once before checking the condition. This makes the do-while loop suitable for situations where there is a need for at least one iteration, even if the total number of iterations is uncertain.

Syntax

It has the following syntax.

Example

do 

{

    // Code to be executed

    // Update expression (if needed)

} while (condition);

Where,

  • Condition: In the do-while loop the condition is checked after the loop body executes at least once. If the condition is true, the loop continues to work until the condition became false. If the condition is false, it exits the loop.
  • Update Expression: It updates the loop variable value, whether it increments or decrements.
  • Body: It is the main body of the program that contains a set of statements that would be executed until the condition remains true.
  • Flow Diagram of Do-while loop in C++

In the flowchart provided, follow these steps to incorporate the do-while loop in C++:

Step 1: First, start the do while loop.

In the succeeding phase, it runs the loop body at a minimum of one time.

Afterwards, it evaluates the specified condition. If the condition evaluates to true, the program proceeds to run the loop body repeatedly until the condition becomes false.

If the condition evaluates to false, it will terminate the loop body.

Step 5: Finally, it prints the output.

Simple do-while loop example

Let's consider a scenario to demonstrate the functionality of the do-while loop in the C++ programming language.

Example

Example

#include <iostream>

int main() 

{

    int q = 1;

    //Initializing the 'q' variable to the value '1'

    do 

    {

        std::cout << "Hello!!" << std::endl;

        q++;  // Update the expression

    } while (q <= 6);  // Checking the Condition

    return 0;

}

Output:

Output

Hello!!

Hello!!

Hello!!

Hello!!

Hello!!

Hello!!

Explanation:

This C++ code illustrates the implementation of a do-while loop to repeatedly output the message "Hello!!". Execution of the loop commences prior to condition evaluation, with the integer 'q' initialized to 1. Each cycle sees an increment in the value of 'q' within the loop, leading to the printing of "Hello!!". The loop persists as long as 'q' remains less than or equal to 6, guaranteeing the message is shown six times. By assessing the condition post-execution, the loop is ensured to iterate at minimum once, irrespective of any modifications to the initial 'q' value.

Nested do-while Loop

In C++ programming, a do-while loop within another do-while loop is referred to as a nested do-while loop. The inner loop must complete all its iterations before the outer loop advances to the next iteration. This setup ensures that the inner loop runs to completion, evaluating its condition as false for each iteration of the outer loop.

Simple Nested do-while Loop Example:

Let's consider a scenario to demonstrate the nested do-while loop in C++.

Example

Example

#include <iostream>

using namespace std;

int main() 

{

    int q = 1;

    //Initializing 'q' to the value '1'.

    do 

    {

        int k = 1;

        //Initializing 'k' to the value '1'.

        cout << "The outer Loop Iteration count is: " << q << std::endl;

        do 

        {

            cout << "   The inner Loop Iteration count is: " << k << std::endl;

            k++;

        } while (k <= 3);  

        //The inner loop executes fully before the outer loop iterates

        q++;

    } while (q <= 2); 

    // Outer loop executes twice.

    return 0;

}

Output:

Output

The outer Loop Iteration count is: 1

   The inner Loop Iteration count is: 1

   The inner Loop Iteration count is: 2

   The inner Loop Iteration count is: 3

The Outer Loop Iteration count is: 2

   The inner Loop Iteration count is: 1

   The inner Loop Iteration count is: 2

   The inner Loop Iteration count is: 3

Explanation:

A do-while loop that is nested is implemented in this C++ program. The internal loop iterates three times (k ranging from 1 to 3) during each cycle, while the external loop iterates twice (q ranging from 1 to 2). The inner loop completes its iterations before the outer loop proceeds to the next cycle. Within the inner loop, the ongoing iterations are tracked, while the outer loop signifies the conclusion of a set of inner loop iterations. The utilization of do-while loops guarantees that the code block executes even if the condition is false initially, as they execute at least once before checking the condition.

Infinite do-while loop

In C++, an endless do-while loop arises when the loop condition remains true consistently. Employing a true condition guarantees the perpetual execution of the loop since do-while loops execute at least once before evaluating the condition. To halt this continuous loop, a break statement or an alternative control method like return or exit is essential.

Syntax:

It has the following syntax.

Example

do 

{    

    // Code lines to be executed.   

} while (true);

Infinite do-while loop Example:

Let's consider a scenario to demonstrate an endless do-while loop in C++.

Example

Example

#include <iostream>

int main()

{

    do

    {

        std::cout << "This loop will run indefinitely.\n";

    } while (true); 

    // The condition always evaluates to true.

    return 0;

}

Output:

Output

This loop will run indefinitely.

This loop will run indefinitely.

This loop will run indefinitely.

This loop will run indefinitely.

Explanation:

This C++ code showcases a perpetual do-while loop. Following a minimum of one iteration, the do segment outputs the message "This loop will continue indefinitely" to the terminal. The loop persists due to the constant truth of the loop condition, leading to an infinite loop. Introducing a break statement into the code or terminating the program manually are the two methods to halt execution. In typical scenarios, the loop remains ongoing, preventing the execution of the return 0 statement.

Examples of the do-while loop

1. Program of Factorial Using do-while Loop:

Let's consider an example to demonstrate the use of a do-while loop in calculating the factorial of a number.

Program

Example

#include <iostream>

using namespace std;

int main() 

{

    int num_ber, factorial = 1, q;

    //Intializing the factorial, num_ber and 'q' variable.

    cout << "Enter a number: ";

    cin >> num_ber;

    q = num_ber;

    do

    {

        factorial *= q;

        q--;

    } while (q > 0);

    cout << "The factorial of a given number " << num_ber << " is " << factorial << endl;

    return 0;

}

Output:

Output

Enter a number: 6

The factorial of a given number 6 is 720

Explanation:

This C++ code utilizes a do-while loop to calculate the factorial of a specified number. Initially, it sets the factorial to 1 based on an integer input (num_ber) provided by the user. Inside the loop, it assigns q to the input number and then updates the factorial by multiplying it with q while decrementing q in each iteration until it hits zero. The do-while loop guarantees that the calculation occurs at least once. Finally, the program displays the computed factorial of the input number.

2. Program of Pyramid Pattern Using do-while Loop:

Let's consider a demonstration to showcase and display the pyramid pattern using a do-while loop.

Program

Example

#include <iostream>

using namespace std;

int main()

{

    int rows, q = 1, k;

    //Initializing the variables rows, 'q' and 'k'.

    cout << "Enter the number of rows: ";

    cin >> rows;

    do 

    {

        k = 1;

        do

        {

            cout << "* ";

            k++;

        } while (k <= q);

        cout << endl;

        q++;

    } while (q <= rows);

    return 0;

}

Output:

Output

Enter the number of rows: 7

* 

* * 

* * * 

* * * * 

* * * * * 

* * * * * * 

* * * * * * *

Explanation:

This C++ code utilizes a do-while construct to showcase a pyramid design angled to the right. Initially, the user inputs the quantity of rows. Subsequently, the internal do-while loop (k) displays the asterisks in each row, while the outer do-while loop (q) ascertains the total row count. With each iteration of the inner loop ranging from k = 1 to q, an asterisk is printed. Following the printing of asterisks for a row, the program transitions to the next line and increments q, persisting until it achieves the designated row count.

3. Program of Multiplication Table Using do-while Loop:

Let's consider an illustration to demonstrate how a do-while loop can be utilized to calculate a multiplication chart.

Program

Example

#include <iostream>

using namespace std;

int main() 

{

    int num_ber, q = 1;

    //Intializing the variable num_ber and 'q'.

    cout << "Enter a number: ";

    cin >> num_ber;

    do 

    {

        cout << num_ber << " * " << q << " = " << num_ber * q << endl;

        q++;

    } while (q <= 10);

    return 0;

}

Output:

Output

Enter a number: 7

7 * 1 = 7

7 * 2 = 14

7 * 3 = 21

7 * 4 = 28

7 * 5 = 35

7 * 6 = 42

7 * 7 = 49

7 * 8 = 56

7 * 9 = 63

7 * 10 = 70

Explanation:

Employing a do-while construct, this C++ code showcases the multiplication table ranging from 1 to 10 based on a user-provided integer input. The multiplier, denoted by q, commences at 1, while the user input gets saved in the variable number. Inside the do block, q is iterated by 1, and the resultant multiplication is displayed. The loop persists until q exceeds 10, ensuring the multiplication table is displayed at least once, even if number happens to be zero, thanks to the nature of the do-while loop.

C++ Do-while loop MCQS

  1. What is the main difference between C++'s while and do-while loops?
  • do-while loop may not run, but the while loop does so at least once.
  • do-while loop executes at least once, but a while may not execute.
  • Both loops are identical in execution.
  • while loop is faster than do-while.
Example

#include <iostream>

using namespace std;

int main() 

{

    int num = 5;

    do 

{

        cout << num << " ";

        num--;

    } while (num > 0);

    return 0;

}
  • 5 4 3 2 1 0
  • 3 4 2 1 5
  • 3 1 4 2
  • 5 4 3 2 1
  1. What is the number of iterations for the loop?
Example

int i = 10;

do 

{

    cout << i << " ";

    i++;

} while (i < 10);
  • Infinite

The output of the provided code will be: c) 1.

Example

#include <iostream>

using namespace std;

int main() 

{

    int num = 3;

    do

 {

        cout << num * 2 << " ";

        num--;

    } while (num > 0);

    return 0;

}
  • 6 4 2
  • 2 4 6
  • 3 2 1
  1. Which of the following statements about a do-while loop is true?
  • The loop executes at least once.
  • The loop may not execute at all.
  • The condition is checked before executing the loop body.
  • The loop never terminates.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience