It is also called as post tested loop. It is used when it is necessary to execute the loop at least one time. Syntax:
Syntax:
do {
Loop body
} while (Expression);
Example:
int main(){
int num,i=0;
do{
printf("To enter press 1\n");
printf("To exit press 2");
scanf("%d",&num);
++i;
switch(num){
case 1:printf("You are welcome\n");break;
default : exit(0);
}
}
while(i<=10);
return 0;
}
Output: 3 3 4 4
If there is only one statement in the loop body then braces is optional.
For example:
(a)
int main(){
double i=5.5678;
do
printf("hi");
while(!i);
return 0;
}
Output: 3 3 4 4
(b)
int main(){
double i=5.63333;
do
printf("hi");
while(!i);
return 0;
}
Output: hi
(c)
int main(){
int x=25,y=1;
do
if(x>5)
printf(" ONE");
else if(x>10)
printf(" TWO");
else if(x==25)
printf(" THREE");
else
printf(" FOUR");
while(y--);
return 0;
}
Output: ONE ONE