do…while loop vs. while loop in C/C++


Here we will see what are the basic differences of do-while loop and the while loop in C or C++.

A while loop in C programming repeatedly executes a target statement as long as a given condition is true. The syntax is like below.

while(condition) {
   statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.

When the condition becomes false, the program control passes to the line immediately following the loop.

Example

#include <stdio.h>
int main () {
   int a = 10; // Local variable declaration:
   do { // do loop execution
      printf("value of a: %d\n", a);
      a = a + 1;
   } while( a < 20 );
   return 0;
}

Output

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Now let us see the do-while loop.

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the 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.

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

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.

Example

#include <stdio.h>
int main () {
   /* local variable definition */
   int a = 10;
   /* while loop execution */
   while( a < 20 ) {
      printf("value of a: %d\n", a);
      a++;
   }
   return 0;
}

Output

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

So the differences are summarized in the following table −

While LoopDo-While Loop
This is entry controlled loop. It checks condition before entering into loopThis is exit control loop. Checks condition when coming out from loop
The while loop may run zero or more timesDo-While may run more than one times but at least once.
The variable of test condition must be initialized prior to entering into the loopThe variable for loop condition may also be initialized in the loop also.
while(condition){
   //statement
}
do{
   //statement
}while(condition);
raja
Published on 29-Apr-2019 12:58:24
Advertisements