Understanding the Do While Loop in C: A Step-by-Step Tutorial
This loop is useful to execute a group of statements repeatedly as long as a condition is true. Once the condition becomes false, the loop terminates.
Syntax: do{
statements;
}while(condition);
First the compiler executes all the statements and then tests the condition.If the condition is true, then it goes back and executes the statements the second time.
If the condition is true, again it goes back and executes the statements. In this way the statements are executed repeatedly aas long as the condition is true. Once the conditition becomes false, the loop terminates.
Example: int digit=0;
do
printf("%d\t",digit+=2);
while(digit<10);
In above eample since only one statement is there inside loop, we need not enclose it in curly braces. In the printf() statement digit+=2 represents that we are adding 2 to digit value and storing it again in digit. It means digit=digit+2.
Now, the digit value becomes 2. In the condition digit<10, it means as long as digit value is less than 10, the loop is repeated. So, it will display even numbers upto 10 as 2,4,6,8,10.
Program to find the sum of digits of a number.
#include<stdio.h>
void main()
{
int num,digit,sum=0;
printf("\n Enter the number:");
scanf("%d",&num);
do{
digit=num%10;
sum+=digit;
num/=10;
}while(num>0);
pritnf("\nThe sum of digits=%d",sum);
}
Output – do while loop in C
Enter a number: 1048
The sum of digits: 13