Friday, July 29, 2016

C Basics - The do-while Loop in C

The loops that we have used so far executed the statements within them a finite number of times. However, in real life programming one comes across a situation when it is not known beforehand how many times the statements in the loop are to be executed.

A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
The syntax of a do..while loop is,

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

The general form of do..while is as shown below:

do
{ 
do this ; 
and this ;
} while ( this condition is true) 

Note that this loop ensures that statements within it are executed at least once before testing condition.

#include <stdio.h>
 
int main () {

   int i = 1;

   do {
      printf("value of i is: %d\n", i);
      i++;
   }while( i < 5 );
 
   return 0;
}
Output of above program,

value of i is: 1
value of i is: 2
value of i is: 3
value of i is: 4

There is a minor difference between the working of while and do-while loops. This difference is the place where the condition is tested. The while tests the condition before executing any of the statements within the while loop. As against this, the do-while tests the condition after having executed the statements within the loop.

This means that do-while would execute its statements at least once, even if the condition fails for the first time. The while, on the other hand will not execute its statements if the condition fails for the first time.



Related topics:
Loops in C   |   The for Loop in C   |   The while Loop in C   |   Nested Loop in C   |   Infinite Loop in C   |   Loop Control Statements in C   |   The break Statement in C   |   The continue Statement in C   |   The goto Statement in C   |   The return Statement in C

List of topics: C Programming

No comments:

Post a Comment