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*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
do
{
printf("Its work!!");
}while(10<1);
getch();
}
Output of above program:
Its work!!
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.*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,f=1;
char choice;
clrscr();
do
{
printf("Enter number : ");
scanf("%d",&n);
while(n>=1)
{
f=f*n;
n--;
}
printf("Factroial value of %d is %d",n,f);
printf("\nCalculate another value y/n :");
scanf("%c",&choice);
}while(choice=='y');
}
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.