do...while Loop in C++ with Example

In the previous post, we covered for loop and while loop, and in this post, we are going to discuss the do...while loop which is a variant of the while loop. 


C++ do...while Loop.

The do...while is known as the exit control loop because the loop executes the block of code once before evaluating the given condition. After executing the code block for the first time it will work like a normal while loop and run the loop as long as the condition is true.

Syntax of do...while Loop.
do {
  // code block
}
while (condition);

Flowchart of do...while loop.
flowchart of do while loop
do...while loop flowchart
Example:
//C++ Example of do while loop 
#include<iostream>
using namespace std;

int main(){

    int i = 1;
    //do while loop
    do{
        cout<<"Do While Loop Code Block";
    }while(i <= 0);

    return 0;
}
Output:
Do While Loop Code Block

Here you can see that the code block is present inside the body of do...while loop executed one time even if the condition is false because the do-while loop checks the condition later after the first execution.  

Example: Program to print multiplication table
//C++ Example of do while loop to print 5 number
#include<iostream>
using namespace std;

int main(){

    int i = 1, num;
    cout<<"Enter a value: ";
    cin>>num;
    //do while loop
    do{
        cout<<num<<" x "<<i<<" = "<<num * i<<endl;
        i++;
    }while(i <= 10);

    return 0;
}
Output:
Enter a value: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Warning: Never write a condition for your loop that will be always evaluated as true else your loop will keep on running for infinite times until your memory gets full. (alert-warning)

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS