do-while Loop in C

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

The do-while loop looks like this:

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

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. This difference is brought about more clearly by the following program.

main( ) 
{ 
while ( 4 < 1 ) 
printf ( "Hello there \n") ; 
}

Here, since the condition fails the first time itself, the printf( ) will not get executed at all. Let’s now write the same program using a do-while loop

main( ) 
{ 
 do 
 { 
 printf ( "Hello there \n") ; 
 } while ( 4 < 1 ) ; 
}

In this program the printf( ) would be executed once, since first the body of the loop is executed and then the condition is tested

Leave a Comment