i2tutorials

do-while loop

do-while loop

 

It is a post-test loop that is closely related to for and while loops. This loop statement tests the condition after the execution of the body of the loop block.

The do keyword is placed on the line of code at the beginning of the loop, and a block of statements follows it with a test condition enclosed within a while statement. Here, the test condition has to be evaluated to true for this construct to iterate after the first time of execution of the block of statements.


The main difference between while and do-while is regarding the position of the test condition. Since the do-while has the test condition at the end of the loop, it is guaranteed that the body of the loop would be executed for at least one time. In contrast with the while, it is possible to enter into the loop/block only if the condition is true.

 

do-while loop

 

Syntax:

 

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

 

Example Program:

 

#include<stdio.h> 
main()
{
int m=2010, n=2016;
do
{ 
if(m%4==0)
printf("\n %d is a leap year",m); 
else
printf("\n %d is not a leap year",m); 
m=m+1;
} while (m<=n);
}

Output:

 

 

 

Exit mobile version