C++

How to Use Do While Loop in C++

In computer programming, loops are specially structured statements that are utilized to execute the program iteratively depending on circumstances. In addition, loops are most commonly used when programmers want to repeat the execution of a block of statements code according to the specified condition.

Moreover, loops are the programming constructs that enable the block of code repetitive execution and provide the easiest way to automate tasks and iterate over data collections. In C++, there are three main types of loops like other programming languages, and “do-while” is one of them.

This guide will cover the following content:

What is a do-while Loop in C++?

The do-while loop is a specific type of loop structure that is utilized in C++ for iterating program execution until a particular condition is satisfied. Moreover, in a do-while loop the provided condition for the loop is verified at the end of each iteration, which makes it different from a while loop.

Scenarios for Using a do-while Loop

When the iteration numbers are not fixed, the do-while loop must be used, and it executed at least once. The C++ compiler first tests the loop body and then executes the condition which indicates that the loop must return a result.

Syntax of do-while Loop in C++

In C++, the basic syntax of the do-while is:

do {
  //code body to be executed
} while (condition);

The description of the above-given syntax is:

  • do” keyword initiates the loop.
  • { }” curly brackets contain the statements that execute it at any cost.
  • While (condition)” is the statement that needs to be checked and returned as true for the loop to continue execution.

Working of do-while Loop in C++

To understand the working of the do-while loop in C++, check out the below-stated detailed explanation:

  • The control of the flow enters the do-while loop.
  • Executes the code statement inside the loop.
  • Loop variable will update according to the values inside the body of a loop.
  • Evaluate the test condition.
  • If the test expression is true, the do-while body will be executed; on the other hand, if the test condition evaluates to false, the flow of the loop will exit and the compiler will run the statements after the loop.
  • The flow of the loop goes back to the second step to execute the body again.

You can demonstrate the above-stated steps using the below-provided flowchart diagram:

Do-while Loop Components In C++

The components of the do-while loop in C++ are provided below:

Components Description
do This block of statements will be executed at least one time and start the do-while loop.
Code block Code block is surrounded by curly braces and must only be executed once.
while This is a loop condition that is checked every execution of the code block that is specified by users.
Semicolon “;” This symbol indicates the conclusion of the do-while loop statement.

Example 1: How to Display Integer Array Element Using do-while Loop in C++?

In this example code, we will print the integer array elements with the help of the do-while loop:

#include <iostream>
using namespace std;

int main()
{
   int my_arr[]={5, 10, 15, 20, 25};
   int x = 0;
   cout<< "The Elements of an Integer Array are: ";
  do
    {
    cout << my_arr[x] << " ";
    x++;
    }
  while( x < 5 );
   cout << endl;
   return 0;
}

Here is an explanation of what the code does:

  • First, added header files and then declared an integer type array with “5” elements. Then, initialized it with values.
  • Next, declared and initialized the integer type variable and added the first “cout” statement.
  • Then, entered a do-while loop that will run at least one time in the program whether the provided condition is true or not.
  • Inside the loop, printed the value of the x-th element of the array using the “cout” stream then utilized the increment operator.
  • Afterward, checked the condition, if the specified condition is true the flow of the loop goes back to the previous step and iterates the loop.
  • If the provided condition is false, the loop will be terminated.
  • Program execution will be ended by returning “0”.

Output

Example 2: How to Display Numbers Until User Entered Correct Value Using do-while Loop in C++?

Let’s take the below-provided code example for printing numbers until users provide the correct value according to the specified condition using the do-while loop:

#include <iostream>
using namespace std;

int main()
{
  int num;
  do {
    cout <> num;
    }
  while (num  10);
    cout << "Your Entered Number is Incorrect..!!" << endl;
return 0;

}

According to the above code:

  • We started the program by including the header file and namespace std.
  • Then, declared the integer variable inside the “main()” function.
  • Next, initiated the do-while loop by utilizing the “do” keyword and used the “cout” stream to prompt the users to add the number.
  • Afterward, added the “cin” statement to scan and saved the input value in the variable.
  • Finally, the loop will check the specified condition that is if the entered number is less than “1” or greater than “10”.
  • Here, if the condition is satisfied (0 and 11) then the loop keeps on running.
  • The loop will be executed until the provided input satisfied (0 and 11) the given condition. Otherwise, the loop will be terminated.

The output of the above-described code has been provided below:

Example 3: How to Display Sum of Users-Input Positive Numbers Using do-while Loop in C++?

By using the do-while you can also print the sum of the users-input positive number in C++. For that purpose, see the following code:

#include <iostream>
using namespace std;

int main()
{
   int v = 0;
   int s = 0;
  do
    {
    cout<> v;
    s += v;
    }
  while(v >= 0);
   cout << "The Sum of Entered Values: " << s << endl;
   return 0;
}

The description of the above-stated code is:

  • Initially, we included the header files. Then, declared and initialized integer type variables with “0”.
  • Next, we added the “do” keyword and used the “cout” statement for taking input from users.
  • After that, once users added the number, the flow passed to the while statement which compares the provided condition. Since the condition is greater than or equal to the “0”, the loop of the above code will continue its execution until the user enters “0” or any other negative number.

The following output will be retrieved by executing the above code:

Nested do-while Loop in C++

In C++, a do-while loop underneath another loop is known as a nested do-while loop. In addition, in the nested do-while loop for the outer loop’s iteration, as well as the inner loop executes several times.

Syntax of Nested do-while Loop in C++

The nested do-while loop has the below-provided syntax in C++:

do {
    //code block of outer loop
do {
   //code block of inner loop
} while (inner_loop_condition);
} while (outer_loop_condition);

Here:

  • First “do” statement represents the do part of the outer do-while loop.
  • Second “do” statement indicates the inner do-while loop.
  • First “while” statement shows the test expression for the outer loop.
  • Second “while” statement indicates the test expression for the inner loop.

Working of Nested do-while Loop In C++

The flow of the nested do-while loop is as follows:

  • The control of the flow enters the outer loop and runs it once.
  • After the execution of the outer loop completes, the flow enters the inner loop.
  • The statements within the inner loop are executed and evaluate its “while” condition.
  • It fully runs the inner loop until the “while” condition is no longer true.
  • Meanwhile, the outer loop condition is evaluated.
  • If the input condition is met, the program flow returns to the second step and the process is repeated. If it is false, the loop will exit and the compiler will run the statements after the loop.

The illustration of a nested do-while is described in the following flowchart:

Example 1: How to Increase and Display Values Between Particular Ranges Using Nested do-while Loop in C++?

Now, explore the provided code example of a nested do-while loop. Here, we will add and show the values by using inner and outer do-while loops until the value for inner and outer loops is less than or equal to the specified condition that is “5”:

#include <iostream>
using namespace std;

int main()
{
 int num1 = 2;
    do{
           int num2 = 3;     
        do{
            cout << num1<<" "<< num2 <<"\n";
            num2++;
        }
        while (num2 <= 5);
        num1++;
    }
    while (num1 <= 5);   
}

In accordance to the above code:

  • First, declared and initialized the integer type variable and then the same inside the outer loop “do” statement.
  • Then, added output stream for printing the outer loop variable value and incremented the variable value.
  • Next, used the “while” loop, checked the condition for the outer loop, and incremented the variable value.
  • Afterward, utilized the “while” loop and checked the condition for the inner loop.

Output

Example 2: How to Print Table of “2” Using Nested do-while Loop in C++?

In this example, we will display the table of “2” with the help of the nested do-while loop in C++:

#include <iostream>
using namespace std;

int main()
{
  int x = 2;
  int y = 1;
   do
   {
     cout << "Table of 2 is: "<< endl;
    do
    {
           cout << x << " x " << y << " = " << x*y << endl;
             y++;
    }
    while (y <= 10 );
        x++;
        y = 1;
        cout << endl;
    }
    while (x <=2);
return 0;
}

Here:

  • We started by adding the header files.
  • Next, we declared two integer type variables “x” and “y” respectively. Then, initialized them with a value.
  • The “x” variable is utilized inside the outer loop to get the integer number that the multiplication table is being shown for.
  • The inner loop iterates through the user’s given input number and prints the multiplication table using the “y”.
  • Every iteration of the outer loop, runs values of “x” from “1” to “2” and the inner loop runs for values of “y” from “1” to “10”.
  • When the inner loop ends, “x” is incremented by “1” through the increment operator.
  • Lastly, we used the output stream to display the output on the console.

Here is the out of the above-given code:

Infinite do-while Loop in C++

In C++, the infinite do-while loop is a scenario where the condition of the loop is always true and the loop will keep executing indefinitely until the memory has been used. Additionally, the infinite do-while loop can be used by setting the condition statement of the loop as true “while(true)” or by not adding the increment/decrement statement in the loop body.

Syntax of Infinite do-while Loop in C++

The general syntax of infinite do-while loop by setting the “while” condition as a true in C++ is:

do {
// code to be executed repeatedly
} while(true);

Setting Condition as True

Check out the following code to understand this concept. Here, we have used the “do” statement which included the text message that will show on the screen after executing the code. Then, we provided the “true” as a condition inside the “while” statement:

#include<iostream>
using namespace std;

int main(){
    do{
        cout<< "Infinite do-while Loop by Setting Condition as True" << '\n';
        }
    while(true);     
}

Output

Eliminating Increment/Decrement Statement

In the following program, we declared the integer type variable and initialize it with value. Then, added the “do” statement which includes the text message that will print on the screen after executing the code. After that, we specified the condition as “x==1” inside the “while” statement with specifying any increment or decrement code blocks:

#include<iostream>
using namespace std;

int main(){
int x = 1;
    do{    
        cout<< "Infinite do-while Loop by Eliminating Increment/Decrement Statement" << '\n';
        }
    while(x == 1);   
}

Output

That’s all about the usage of the do-while loop in C++.

Wrapping Up

The loops are the programming constructs that enable the block of code repetitive execution and offer the easiest way to iterate over data. The do-while loop is one of them which is a specific type of loop structure that is used in C++ for repeating the program execution until a provided condition is satisfied. The C++ compiler first tests the loop body and then executes the condition which indicates that the loop must return a result.

According to the syntax of the do-while loop, it contains a condition that requires to be verified, statements to be executed iteratively, and ascending or descending operations at the end. In this comprehensive guide, we have described the syntax of the do-while loop and its usage with the aid of the example.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.