Do-While Loop in C

Do-while loop in C is similar to while loop, it is also known as a condition-controlled loop. In the do-while loop, statements executed first, after that, the condition is tested. It means the block of the code is executed at least once, even when the condition is false. Do while loop must be terminated with a semicolon ( ; ).

Syntax of Do While

do
{
	//statements
}while(condition);

Example 1: C program to print 1 to 10, using do-while loop.

#include<stdio.h>
int main()
{
int n=1;
do
{
	printf("%d\n",n);
	n++;
}while(n<=10);
return 0;
}

Example 2: C program to calculate sum of infinite numbers, until user input is not equal to 0. Using do-while loop.

#include<stdio.h>
int main()
{
int n,s=0;
	do
	{
		printf("\nEnter a number: ");
		scanf("%d",&n);
		s=s+n;
	}while(n!=0);
	
	printf("Sum of Numbers : %d",s);
return 0;
}
Sample Output:
Enter a number: 1 Enter a number: 2
Enter a number: 3
Enter a number: 0
Sum of Numbers : 6

Above program will accept user input, infinite times, and calculate the sum of the numbers. If you want to stop the loop, you need to enter 0 as user input.

Difference between while and do-while loop

While Do-While
The while loop test the condition at starting of the loop.In do-while, the condition is checked at the end, after all the statements executed.
If the condition is false in while loop, not a single statement will execute.In do-while, even the condition is false, all the statements will executed at least once.