Looping statement defines a set of repetitive statements . These statements are repeated, with same or different parameters for a number of times. do...while is an exit controlled looping statement. We use do...while loop when there is a need to check condition after execution of loop body
C programming supports three types of looping statements for loop, while loop and do...while loop. Among three do...while loop is most distinct loop compared to others.
Looping statements whose condition is checked after execution of its loop body is called as Exit controlled loop.
We use do...while loop if we need to execute loop body minimum once.
Syntax of do...while loop
do
{
// Body of do while loop
} while (condition);
Parts of do...while loop
Similar to while, do...while loop contains two parts - body of loop and loop condition.
Similar to while you can put loop counter variable-initialization statement before loop and variable-update before end of do...while loop.
Be careful while writing do...while loop. Unlike other two loops do...while contain semicolon at the end.
How do...while loop works?
do...while loop works in two step.
The above two steps are repeated until loop condition is met.
Flowchart of do...while loop
Example to demonstrate do...while loop
Let us write a C program to print natural numbers from 1 to 10 using do...while loop.
/**
* C program to print natural numbers using do while loop
*/
#include <stdio.h>
int main()
{
/* Loop counter variable declaration */
int n=1;
do
{
/* Body of loop */
printf("%d ", n);
/* Update loop counter variable */
n++;
} while(n <= 10); /* Loop condition */
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10