Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Do While - 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

do...

while loop

The do..while loop is similar to the while loop with one important difference. The body of
do...while loop is executed at least once. Only then, the test expression is evaluated.

The syntax of the do...while loop is:

do
{
// statements inside the body of the loop
}
while (testExpression);

How do...while loop works?

 The body of do...while loop is executed once. Only then, the test expression is evaluated.
 If the test expression is true, the body of the loop is executed again and the test
expression is evaluated.
 This process goes on until the test expression becomes false.
 If the test expression is false, the loop ends.

Flowchart of do...while Loop

Example 1: do...while loop


// Program to add numbers until the user enters zero

#include <stdio.h>
intmain()
{
double number, sum = 0;

// the body of the loop is executed at least once


do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

Example 2

#include <stdio.h>
Int main()
{
int counter;
int marks;
int total;
int average;
total = 0;
counter =1;
do
{
printf(“enter marks”);
scanf (“%d”,&marks);
total= total +marks;
counter = counter+1;
}
while (counter<=10)

average=total/counter;
printf(“class average is %d\n”, average);
return 0;
}

Example 3
#include <stdio.h>
intmain()
{
inti = 1;

do
{
printf("%d\n", i);
++i;
while (i<= 5)
}

return 0;
}

You might also like