THE DO ..... WHILE STATEMENT


THE DO ..... WHILE STATEMENT

In while loop a test condition is checked before the loop is executed. Therefoere, the body of the looop may not be executed at all if the condition is not satisfied at the very first attempt. On some occations it might be necessary to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do statement. The takes the form:

do
{
body of the loop
}
while(test-condition);

On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test-condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true.
When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. Since the test-condition is evaluated at the bottom of the loop, the do ... while construct provides an exit-controlled loop and therefore the body of the loop is always executed at least once.

/* Program to demonstrate  do - while
 program to print menu */
#include<stdio.h>
#include<conio.h>
main()
{
int choice,x,y;
char c='y';
clrscr();
printf(" enter the two numbers :");
scanf("%d %d",&x,&y);
do
{
printf("---------  MENU   ----------\n");
printf("     1 .  ADD   \n");
printf("     2 .  SUB   \n");
printf("     3 .  MUL   \n");
printf("     4 .  DIV     \n");
printf("     5 .  EXIT   \n");
printf(" enter your choice  :");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n sum= %d ",x+y);
               break;
case 2: if(x>y)
               printf("\n difference = %d ",x-y);
               else
               printf("\n difference = %d",y-x);
              break;
case 3: printf("\n multiplication = %d ",x*y);
              break;
case 4: if(y!=0)
               printf("\n division = %d ",x/y);
               else
               printf("\n infinity ");
               break;
case 5: exit(0);
default: printf("\n invalid in-put");
               break;
fflush(stdin);
printf(" do u want to continue (y/n) :");
scanf("%c",&c);
}while(c=='y'||c=='Y');
getch();
}

Comments