Cpp Do While Loop

Hi! today we will learn C++ Do While Loop and this loop is a variant of the while loop.

This loop will execute the block of code for once time. before checking if a condition is true,

C++ Do While Loop

Then it will repeat the loop as long as the condition is true, Now I am showing you the Syntax of Do While loop:

do
{
   // Block of code to be executed...
} while (condition);

I hope you note my style of writing code, It can not be effect on the execution of program,

Everybody can develop own style, Now I am Explaining the Example of Do While Loop.

Note: Do While loop will always be executed at least once, even if the condition is false. because the code is executing before the condition is tested.

So, see Example 1:

#include <iostream>
using namespace std;

int main()
{
    int x = 0;
    do
    {
        cout << x << '\n';
        x++;
    } while (x < 10);
    return 0;
}

Then, The Output will be:

0
1
2
3
4
5
6
7
8
9

In the above example 1, we did: First, we declare the integer variable named x and assign the value 0,

then, we start the do-while loop with do keyword and then put the open curly braces, C++ Do While Loop,

In the next line, we give the output operator cout and display the value of x and put the line break operator \n with single quotation

So, In the next line, we use the increment operator ++ with our variable x, this operator will increase value-

-sequence wise. Then use the close curly brackets and put the loop condition with the while loop and-

-the condition is x is Less than 10. Now we are doing an example 2 with the condition is false.

#include <iostream>
using namespace std;

int main()
{
    int y = 7;
    do
    {
        cout << y << '\n';
        y++;
    } while (y < 3);
    return 0;
}

Then, the output:

7

In the Above Example 2, we tested the loop, if the condition is false, So, the result is here. Please do more examples and practice for self learn and improve your concepts .

Today, we have covered the Do While loop topic, if you want to learn While Loop topic then sees our recent topic post.

By Usama Arshad

It's me Usama Arshad working as a Lecturer C++. I am a student of BSIT.

Leave a Reply

Your email address will not be published. Required fields are marked *