Programming in "C‟ | Describe with example in which case do-while loop is most suitable than while loop.

Describe with example in which case do-while loop is most suitable than while loop.

Do while example is best suitable when at least one iteration is required, because it is an exit controlled loop, in the sense, the condition is checked at the end. 

Example: A menu driven program which shows options for result of any one arithmetic operation as per the selection: 

#include<stdio.h>
#include<conio.h>
void main ()
{
int a,b,ch=0;;
clrscr();
printf("enter number 1");
scanf("%d",&a);
printf("enter number 2");
scanf("%d",&b);
do
{
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: {
printf("Addition : %d\n",(a+b));
break; }
case 2: {
printf("Subtraction : %d\n",(a-b));
break; }
default: {
printf("Bye");
break; }
}}while(ch<3);
getch();
}

In the above example, menu will be displayed without checking any condition. Depending upon user's choice a case from switch will execute. If user wish to continue then while loop takes the control
back to do statement.  

Post a Comment

0 Comments