- An Exit Control Loop checks the condition for exit and if given condition for exit evaluate to true, control will exit from the loop body else control will enter again into the loop.
- Such type of loop controls exit of the loop that’s why it is called exit control loop.
Do…While loop:
- Do …while loop is an exit control loop.
- It is a variation of while loop.
- When we want to execute or perform some task at least for once, we can use do…while loop structure.
- In a while loop if the expression becomes false at very first try then loop will never be executed.
- Since, do…while is of type exit control loop it checks the condition at last so, first time the loop will be execute unconditionally.
- If the condition for the exit becomes true then loop will be terminate otherwise it will be executed for the next time.
- It has the following form:
Syntax:
do
{
//loop body
} while (expression);
- The main difference between while loop and do… while is as follow.
While loop | Do…while loop |
---|---|
It is an entry control loop. | It is an exit control loop. |
In while loop expression/condition is checked at the time of entry. | In do… while loop condition is checked at the time of exit. |
It does not have semicolon (;) at the end of the expression. | In do while loop semicolon (;) at the end of the expression is compulsory. |
Syntax: while(condition) { // loop body } |
do { // loop body } while(condition); |
Example: while(i<=5) { printf(“\n%d”,i); i++; } |
do { printf(“\n%d”,i); i++; } while(i<=5) ; |
The following program demonstrates use of do…while loop to perform basic operations.
/* C program to demonstrate the use of do..while loop to perform basic arithmetic operations. */
#include "stdio.h"
#include "conio.h"
void main()
{
float x, y, ans;
int choice;
do
{
printf("\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exit);
printf("\nEter Your Choice:");
scanf("%d", &choice);
if(choice!=5)
{
printf("\n Enter X and Y: " );
scanf("%f %f", &x, &y);
}
switch(choice)
{
case 1:
ans = x + y;
break;
case 2:
ans = x - y;
break;
case 3:
ans = x * y;
break;
case 4:
ans = x / y;
break;
case 5:
exit(0);
default:
printf("\n Invalid choice!");
}
printf("\n Answer is %.2f", ans );
getch();
} while(choice!=5)
}