7.2 – do while iteration statement

by subbu on October 5, 2013

do-while iteration statement in C language:

In the previous session we have discoursed the while loop. It doesn’t execute even at least once if the condition is false. Some times we need a loop that executes at least once before checking the condition.
do-while is an exit control iteration statement checks the condition after the completion of first iteration and while coming out of the loop. If the condition is true then goes to the beginning of the loop to continue iterations otherwise terminates the execution of loop.
It is so important to note that the conditional statement of do-while iteration statement must be terminated with a semicolon.

do while iteration statement

Let us see the difference among while and do-while iteration statements using a simple example.

#include<stdio.h>
int main()
{
  while(10>40)           /* condition is false */
  {
    printf("Hello World");
  }
printf("\nEnd of program..");
return 0;
}

Output:
End of program..

Here the control doesn’t enter into the loop at all, as the condition is checked at the entry point.

#include<stdio.h>
int main()
{
  do
  {
    printf("Hello World");
  }while(10>40);         /* condition is false */
printf("\nEnd of program..");
return 0;
}

Output:
Hello World
End of program..

Here the condition is checked after the completion of first iteration, not proceeded to the next iteration as the condition is false. But, at least one iteration is guaranteed in do-while iteration statement.

do-while is mostly used in situations where need to take a choice from the user and then proceed. Now we will see a couple of examples where we really need do-while iteration statement.

Specification:
Accept numbers, as long as user selects yes (y) and print the sum of all the numbers.

#include<stdio.h>
int main()
{
char ch;
int n,sum=0;
 do{
     printf("Enter the number:");
     scanf("%d",&n);
     fflush(stdin);        /* to not consider enter as a character */
     sum+=n;               /* sum=sum+n; */
     printf("Want to continue (y/n):");
     scanf("%c",&ch);
   }while(ch=='y');
printf("Sum of all the numbers %d",sum);
return 0;
}

Execution:
Enter the number:12
Want to continue (y/n):y
Enter the number:45
Want to continue (y/n):y
Enter the number:78
Want to continue (y/n):n
Sum of all the numbers 135

Here in this example accepting a number and taking choice from the user for every iteration. Loop terminates only when users choice is other than ‘y’ and the condition is false.

Specification:
Demonstrate the simple bank operations like accepting the opening balance, withdraw, deposit and current balance using a menu driven program. Make sure that minimum balance must be more than or equal to 500.

#include<stdio.h>
int main()
{
int ch;
int amt,bal;
/* accepting opening balance */
begin:
printf("Enter the opening balance:");
scanf("%d",&bal);
if(bal<500) /* checking for valid minimum balance */
{
   printf("Minimum balance must be 500... \n");
   goto begin;   /* goes to the 7th line */
}
/* to perform operations */
do{
     printf("1. Deposite\n2. Withdraw\n3. Display\n4. Exit\nEnter your choice 1..4:");
     scanf("%d",&ch);                    /* taking the choice */
     switch(ch)
     {
         case 1:                         /* deposit case */
           printf("Enter the amout:");
           scanf("%d",&amt);
           bal+=amt;                     /* adding amount to balance */
           break;
        case 2:                          /* withdraw case */
           printf("Enter the amount:");
           scanf("%d",&amt);
           if(bal-amt<500)               /* checking for minimum balance */
              printf("In sufficiant balance!!!!\n");
           else
              bal-=amt;                 /* deducting amount from balance */
           break;
        case 3:                         /* displaying the balance case*/
           printf("The current balance is %d\n",bal);
           break;
        case 4:                         /* exit case */
           goto out;                   /* sends the control out of loop */
        default:
           printf("Invalid choice...\n");
     }
}while(1);  /*always true  */
out:
printf("Thank you....");
return 0;
}

Execution:
Enter the opening balance:250
Minimum balance must be 500/- …
Enter the opening balance:1000
1. Deposite
2. Withdraw
3. Display
4. Exit
Enter your choice 1..4:1
Enter the amout:1500
1. Deposite
2. Withdraw
3. Display
4. Exit
Enter your choice 1..4:3
The current balance is 2500
1. Deposite
2. Withdraw
3. Display
4. Exit
Enter your choice 1..4:2
Enter the amount:2100
In sufficiant balance!!!!
1. Deposite
2. Withdraw
3. Display
4. Exit
Enter your choice 1..4:2
Enter the amount:2000
1. Deposite
2. Withdraw
3. Display
4. Exit
Enter your choice 1..4:4
Thank you….

Here we find reasonable usage of goto for two times.

begin:
printf("Enter the opening balance:");
scanf("%d",&bal);
if(bal<500)
{
   printf("Minimum balance must be 500... \n");
   goto begin;
}
do{
     printf(".........

Here user gives the opening balance, if it is more than or equal to 500 then proceeds to do-while loop otherwise goes back to begin.

do{
     --------
     switch(ch)
     {
         ---------
         ---------
       case 4:
         goto out;
         ---------
     }
}while(1);
out:

When user selects 4th choice to exit from the program, the control must come out of the do-while. The break; only sends the control out of switch-case but resumes the execution of do-while. Here goto is only the way to send the control out of do-while.

Quiz:
1) What would be the output of following program?

#include<stdio.h>
int main()
{
int x=5;
do{
    printf("\t%d",x);
    x+=2;
}while (x<=10);
return 0;
}
Show Answer
Output:
5        7        9

Here the x is initialized with 5, printing and incrementing by 2 for every iteration. It is happening as long as the value of x is less than or equal to 10.

2) What would be the output of following program?

#include<stdio.>
int main()
{
int x=5;
do
   printf("\t%d",x--);
while (x);
return 0;
}
Show Answer
Output:
5        4        3        2        1

Here we have not placed the printf() statement with in {}, it is not needed for a single statement.

The variable x is initialized with 5, printing and decrementing the value of x by 1 for every iteration. The loop is terminated when x is 0 (false).

3) What would be the output of following program?

#include<stdio.h>
int main()
{
int x=5;
do printf("\t%d",x--); while(x);
return 0;
}
Show Answer
Output:
5        4        3        2        1

It is absolutely correct, we can write parts of do-while statement in a single line but, make sure that a space is given in between.

4) What would be the output of following program?

#include<stdio.h>
int main()
{
int x=5;
do
{
  printf("\t%d",x-=2);
}while(x);
return 0;
}
Show Answer
Output:
Infinite loop

Here x is started from 5, printing and decrementing by 2 for every iteration. The condition will never be false(0) because x goes like 5  3  1  -1  -2 ……

5) What would be the output of following program?

#include<stdio.h>
int main()
{
  do
  {
     printf("Hello World");
  }while(0)
return 0;
}
Show Answer
Output:
Error

The while statement must be terminated with a semicolon.

Previous post:

Next post: