Loops 2: Do-While
Submitted by M E Senturk on Fri, 09/18/2009 - 15:41
Do while is another repetition statement in c language. It is similar to while by writing but in usage, it is very different. While loop checks the termination condition at the top of the loop. If the test condition returns false, while loop will not run. But if you use do-while loop, even if the test condition returns false, loop runs one time. Basically do-while loops run at least one time.
do
{//do something;
//do something about test variable;
}while(test_condition);
Let's write some code to calculate the perimeter of a polygon.
#include <stdio.h>
int main()
{int size = 0;
float len, P=0;
printf("enter the edge amount of the thing:"); scanf("%d",&size);if(size<3)
{ printf("This is not a polygon you liar!)}
else
{ do{ printf("Enter the edge : "); scanf("%f",&len);P+=len;
size--;
}while(size>0);
printf("Perimeter is %f\n",P);}
return 0;
}
In this code, first we took the lenght of the first edge. Then added it to the sum of edges, perimeter, and decreased the amount of edges.If we use while for the loop, program will return once again to the top of the loop to check the termination criterion.
