
C Programming Do While Loop
Table of Contents
A loop in a C program do…while is guaranteed to execute at least once. In this chapter you do…while will learn to create loops in C programs.
A loop is used to repeat a specific block of code until an end condition is reached. There are three types of loops in C programming:
1. For Loop
2. While Loop
Syntax of do...while loop in C Programming
do
{
// This code will execute
}
while (testExpression);
do…while Loops and while loops are similar except for one important difference. do…while The loop code block is executed onnce before checking the test Expression. So do…while the loop executes at least once.
How do do...whille loops work in C programming?
- The code block inside the second parenthesis is executed once first.
- Then test Expression is evaluated. If test Expression is true then the body of the loop is executed again. This process continues until the test expression returns false.
- do...while The loop terminates when the tst expression returns false of the value is 0(zero).
Example 1: do...while loop
// // C program to output integers 1 to 5
#include
#include
int main()
{
int i;
clrscr();
i=1;
do
{
printf("\n%d",i);
i++;
}
while(i<=5);
getch();
}

output
1
2
3
4
5
Example 2: do...while loop
// Program to sum until user enters 0(zero).
#include
int main()
{
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: 3
Enter a number: 5.5
Enter a number: -5
Enter a number: 10
Enter a number: -3.5
Enter a number: 0
Sum = 10
When the value of test Expression is True and when it is False is discussed in the Relational and Logical Operators page.