Do while loop in c programming; Through this tutorial, you will learn how to use do while loop in C programming with c program examples.
Do While loop in C Programming
- Do While loop in c definition
- Syntax of do while loop in c
- Example 1 – C Do while loop Program Example
- Example 2 – C program to reverse a number using do while loop
Do While loop in c definition
The c do..while loop is similar to the while loop with one exception. The body of do...while loop is executed at least once. Only then, the test expression is evaluated.
In other words, The C do while loop executes the first body of code. Then evaluates to test expression.
Syntax of do while loop in c
The syntax of the C do...while loop is:
do
{
//Statements
}while(condition test);
Explanation of above given c do while loop syntax
- The body of code executed first. Then, the
testExpressionis evaluated. - If
testExpressionis true, the body of the loop is executed again andtestExpressionis evaluated once more. - This process continues until TestExpression is found to be false.
- If
testExpressionis false, the loop terminate.
Example 1 – C Do while loop Program Example
See the following simple program in c using do while loop; as shown below:
// Program to add numbers until the user enters zero
#include <stdio.h>
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: 10 Enter a number: 1 Enter a number: 4 Enter a number: 4 0Enter a number: 0 Sum = 19.00
Example 2 – C program to reverse a number using do while loop
See the following c program to reverse a number using do while loop; as shown below:
#include <stdio.h>
int main()
{
int num = 123;
int reverse=0,rem;
printf("You number is 123 \n");
do{
rem=num%10;
reverse=reverse*10+rem;
num/=10;
}while(num!=0);
printf("Reverse number is %d\n",reverse);
return 0;
}
Output
You number is 123 Reverse number is 321