DO-WHILE in C lang
Posted by
Ravi Kumar at Thursday, September 1, 2011
Share this post:
|
The while loop we studied just before makes a test condition
before loop executed. Therefore the body of loop may not
be executed at all if the condition is not satisfied at the
first attempt.On same occasions it might be necessary to
execute body of the loop before test is performed Such
conditions can be handled using do statement.This takes
the form
do
{
body of the loop.
}while(test-condition)
Here the test-condition in the while statement is
evaluated at the end of the
loop is executed
once if the test cndition is wrong.For first attempt
otherwise the program continues to evaluate the body
of as long as condition is true. The do-while is an
exit control loop.there fore the body of the loop is
executed at least once.
Example:
Program to find sum of n numbers.
#include
main( )
{
i=1;
sum=0;
do
{
sum=sum+i;
i=i+1;
}
while(sum<40 || i<10);
printf ("%d%d\n",i,sum);
}
The loop will be executed as long as one of the two
relations is true.