Definition: The do-while loop is an exit-controlled loop in which the loop body executes first and the condition is checked afterward.
Definition: The do-while loop is an
exit-controlled loop in which the loop body executes
first and the condition is checked afterward.
do
{
statements;
}
while (condition);
The following program prints the value of i and increases
it until i becomes greater than 5.
#include <stdio.h>
int main()
{
int i = 1;
do
{
printf("%d ", i);
i++; // move to the next number
}
while (i <= 5);
return 0;
}
1 2 3 4 5
The condition of a do-while loop is checked
after the loop body executes. Therefore, the
body always executes at least once.
do block are executed once before the condition
is checked.
A menu-driven program often needs to display the menu at least once before asking whether the user wants to continue.
Write a C program that repeatedly accepts numbers from the user and displays the entered number until the user enters 0.
do-while loop.
Read a number inside the loop, display it when it is not zero,
and continue while the number is not 0.
A do-while loop executes its body first and checks
the condition afterward. Therefore, the loop body is guaranteed
to execute at least once.
#include <stdio.h>
int main()
{
int num;
do
{
printf("Enter a number (0 to stop): ");
scanf("%d", &num);
if (num != 0) // 0 is the sentinel, so skip printing it
printf("You entered: %d
", num);
} while (num != 0); // condition is checked after the body
printf("Loop terminated.
");
return 0;
}
Enter a number (0 to stop): 5 You entered: 5 Enter a number (0 to stop): 8 You entered: 8 Enter a number (0 to stop): 0 Loop terminated.
Unlike a while loop, a do-while loop
always executes its body at least once because the condition is
checked after the body.
| while | do-while |
|---|---|
| Entry-controlled loop. | Exit-controlled loop. |
| Condition is checked before the body. | Condition is checked after the body. |
| May execute zero times. | Executes at least once. |
Syntax starts with while. |
Syntax starts with do and ends with while. |
do-while is an exit-controlled loop.while(condition).| Concept | Remember |
|---|---|
| do-while | Exit-controlled loop. |
| First step | Execute the loop body. |
| Second step | Check the condition. |
| Minimum execution | At least once. |
Watch a beginner-friendly explanation of the do-while loop in C.
A short handwritten-style revision sheet for the do-while loop will be provided here.
Use the mind map for quick revision of do, condition, repetition and exit.