What is a do–while Loop?
A do–while loop is a looping statement that executes the loop body at least once, and then checks the condition.
Key idea:
Condition is checked after execution, not before.
Why do–while is different from while
whileloop- → Condition checked before execution
- → Loop may run zero times
do–whileloop- → Condition checked after execution
- → Loop runs at least one time
Syntax of do–while Loop
do {
// statements
} while (condition);Important:
- Semicolon
;afterwhile(condition)is mandatory
Simple Example: Print numbers 1 to 5
c
1
2#include <stdio.h>
3
4int main() {
5 int i = 1;
6
7 do {
8 printf("%d\n", i);
9 i++;
10 } while (i <= 5);
11
12 return 0;
13}Output
1
2
3
4
5Step-by-Step Working
- Loop body executes first
- Value is printed
- Variable is updated
- Condition is checked
- If true → repeat
- If false → loop stops
Proof that do–while runs at least once
int i = 10;
do {
printf("Hello");
} while (i < 5);Output
HelloEven though the condition is false, the loop runs once.
When to Use do–while Loop
Use do–while when:
- You must execute code at least once
- Menu-driven programs
- Input validation
- User interaction systems
Example:
- Show menu once, then ask user whether to continue
while vs do–while
| Feature | while | do–while |
| Condition check | Before loop | After loop |
| Minimum execution | 0 times | 1 time |
| Loop type | Entry-controlled | Exit-controlled |
