C++ do-while loop

  • The do-while loop is similar to while loop except that do-while loop executes the body of the loop at least once whether the condition is true or not.
  • do-while loop checks the condition after the execution of body so it is called as exit level looping statement.
  • The basic syntax of the do-while loop is as follows:
  • Syntax

    do while (condition)

    {

    Loop-body

    }while(condition);
  • Here you can see the condition is present at the end so the loop body certainly executes once. When condition becomes false the program flow jump on the statement just after the do-while loop. Here is a diagram which shows the concept of do-while loop:
  • loop

    Here is an example-program of do-while loop which prints the value from 1 to 5:

    Example

    #include<iostream.h>

    #include<conio.h>

    int main()

    {

    int i=1;

    do

    {

    cout<<"\n"<<i;

    i=i+1;

    }while(i<=5);

    getch();

    return 0;

    }

    Output

    The output of the above program is as follows:

    1

    2

    3

    4

    5