Table of Contents
Both while and do-while loops repeat a block of code while a condition remains true. The main difference is when the condition is evaluated.
#include <stdio.h>
int main()
{
int i = 6;
while (i <= 5)
{
printf("while: %d\n", i);
}
do
{
printf("do-while: %d\n", i);
}
while (i <= 5);
return 0;
}
Example Output #
do-while: 6
Explanation #
The while loop evaluates its condition before executing the body:
while (i <= 5)
Since i is 6, the condition is false and the loop body does not execute.
The do-while loop evaluates its condition after executing the body:
do
{
printf("do-while: %d\n", i);
}
while (i <= 5);
Therefore, its body executes once even though i <= 5 is false.
while |
do-while |
|---|---|
| Condition checked before the body | Condition checked after the body |
| May execute zero times | Executes at least once |
| No semicolon after the condition | Semicolon required after the condition |