Friday 29 October 2010

do..while loop

definition
syntax
flowchart
example
More examples on do..while loop

definition

In C, do...while loop is very similar to while loop. Only difference between these two loops is that, in while loops, test expression is checked at first but, in do...while loop code is executed at first then the condition is checked. So, the code are executed at least once in do...while loops.
Syntax 

do
{
   some code/s;
}while (test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s inside body of do are executed again and the process continues until test expression becomes false(zero).


flowchart


example

Write a C program to add all the numbers entered by a user until user enters 0.

/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
int main(){
   int sum=0,num;
   do             /* Codes inside the body of do...while loops are at least executed once. */
   {                                    
        printf("Enter a number\n");
        scanf("%d",&num);
        sum+=num;      
   }
   while(num!=0);
   printf("sum=%d",sum);
return 0;
}

Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1

In this C program, user is asked a number and it is added with sum. Then, only the test condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to 0, the body of do...while loop is again executed until num equals to zero.

Statements
looping statements

 do-while

No comments:

Post a Comment