Thursday 12 March 2015

Difference between while, do-while and for with example

1. while and for are entry control loop whereas do-while is an exit control loop

2. the program illustrates the working. The program is to calculate the sum of n nos. using while, do-while and for.

#include<stdio.h>
 int main()
 {
     int i,j=0,n=3;
     for (i=1;i<=n;i++)
     {
        j+=i;
     }
     printf("\nFor sum= %d",j);
     i=1;
     j=0;
     while(i<=n)
     {
        j+=i++;
     }
     printf("\nWhile sum= %d",j);
     i=1;
     j=0;
     do
     {
        j+=i++;
     }while(i<=n);
     printf("\nDo-While sum= %d",j);
     return(0);
 }


3.
a)Output of the above program when n=3:
For sum= 6
While sum= 6
Do-While sum= 6

b)Output of the above program when n=0:
For sum= 0
While sum= 0
Do-While sum= 1

observing the output we can find that for and while do not run n=0 but do-while did run.

No comments:

Post a Comment