Now we know about for, while loop that executed the statement within them finite number of times. However, in real life programming, one comes across a situation when it is not known beforehand how many times the statement in the loop are to be executed. In this situation we used do-while loop.
do-while tests the condition after having executed the statement within the loop i.e. do-while would executed its statement at least once, even if the condition fails for the first time. For example notice in following program:
/*demonstration of do-while*/
Output of above program:
In above program, the printf() would be executed once, since first the body of loop is executed and then the condition tested, 10<1 condition false so loop terminate and go to next statement.
/*program to find factorial value of any number, and it is execute unknown number of times when user enter no, then program should be terminate.*/
printf("Enter number : ");
printf("Factroial value of %d is %d",n,f);
printf("\nCalculate another value y/n :");
output of above program:
Enter number :5
Factorial value of 5 is 120
Calculate another value y/n :y
Enter number :4
Factorial value of 4 is24
Calculate another value y/n :n
In above program, the do-while loop would keep getting executed till the user continues to answer y. When user enter answer n,the loop terminate, since the condition fails.