do…while loop

This loop is different from the other two loop (for, while), initially the variable is initialize, then the body of loop is execute, then the condition is checked.

In this loop is definitely executable whether the condition is true or false whereas the other two The first condition is checked in the loop and then the body of loop is executed.

The example is given below.

SYNTEX:

initialization;
do 
{
 Body of loop;
 updation;
} while (expression);

do-while-loop

Example:-

#include<iostream.h>
#include<conio.h>

 void main()
{
 clrscr();
 int x;
 cout<<"Enter number: ";
 cin>>x;

 int i=1;

  do {
       cout<<i<<" do while<<endl;       // body of loop
       i++;                       // increment by one digit
    } while(i<x);            //expression
 
getch();
}
OUTPUT:-
1st RUN
Enter number: 3
1 do-while
2 do-while
3 do-while

2nd RUN
Enter number: 1
1 do-while
explanation

Here do-while loop will work as fallows,

do-while-loop-in-cpp

In 1st Run,

the input value 3 is first given by the user, after which the execution goes to loop where we have assigned value 1 to a variable i.

After this execution goes to the body of loop and prints the value of variable x.

After this there is increment in the expression value 1, then

the condition is checked because condition is going to be true (1 <3) so execution goes back to the body of loop and prints the value of x variable again,

this sequence moves As long as the condition false (3 <3) does not happen. Because the condition here is being true three times, so here the body of loop (3) times is execute only.

increment in initialization value(i=0) condition check(i<x) body of loop execute

increment in initialization value(i=1) body of loop (i do-while) condition check
1 1 do-while 1<3 (True)
2 2 do-while 2<3 (True)
3 3 do-while 3>3 (False)

 2nd Run,

the user-input value is 1 and after that the body of loop is executed,

then in the body of loop there is increment in the initialization value and

then the condition check is going to be false here.

There is one time execution even after the condition is false, which separates it from the other two loop for and while.

increment in initialization value(i=1) body of loop (i do-while) condition check
1 1 do-while 1<1 (False)

 

do-while loop is different from for and while loop

  • In the first two loop (in for and while loop) the first condition is checked, then the body of loop is execute, then the initialize value of the loop is incremented, whereas in the do-while loop, the first body of loop is executed, then the condition is checked Then there is increment in the initialize value in the last.
  • and also updation in body of loop in the do-while loop.

 

Related Exercise


previous- while-loop

next-break | goto Statement