C++ do-while loop

A do-while loop is similar to a while loop, except that a do-while loop is guaranteed to execute at least one time. The conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.

Syntax :

do
{
    statement(s);
} while( condition );

Example :

#include <iostream>
using namespace std;
int main ()
{
    // declared local operand (variable)
    int a = 1;

    // do-while loop
    do
    {
        cout<<"value of a: "<<a<<"\n";
        a = a + 1;
    } while( a < 5 );

    return 0;
}

Output :
 value of a: 1
 value of a: 2
 value of a: 3
 value of a: 4
One more Example where condition is false :

#include <iostream>
using namespace std;
int main ()
{
    // declared local operand (variable)
    int a = 1;

    //here, Condition is false. a is not equals to zero
    do
    {
        cout<<"value of a: "<<a<<"\n";
        a = a + 1;
    } while( a == 0 );

    return 0;
}

Output :
 value of a: 1

0 Comments