The do-while Loop in C

Rate this post

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.

Let’s see the execution flow:

do
{
this ;
and this ;
and this ;
you can add many statement;
}

while ( this condition is true ) ; 

 

the do while loop execution flow
the do while loop execution flow

Point to be noted

  • 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.

Difference Between while loop and do while

Let’s have an example to clear the difference between while loop and do while

The while loop

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.

The do while loop

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

  • In the above program the printf( ) would be executed once, since first the do loop is executed and then the condition is tested.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: