top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why we use do-while loop in c? Explain with Example?

+2 votes
763 views
Why we use do-while loop in c? Explain with Example?
posted Jun 1, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

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

answer Jun 2, 2015 by Manikandan J
0 votes

If a user want to execute statements present within the loop at least once then they prefer using do-while.
Major difference between while and do-while is
1- while first check then take action action
2- do-while first executes statements then condition is checked.

answer Jun 1, 2015 by Vikram Singh
...