Syntax
A do-while loop executes the body at least once, then checks the condition.
do {
// runs at least once
} while (condition);
Difference from While
| Feature | while | do-while |
| Condition check | Before body | After body |
| Minimum executions | 0 (may never run) | 1 (always runs once) |
| Use case | Unknown iterations | Must run at least once |
Example
void main() {
// Basic do-while
int i = 1;
do {
print('i = $i');
i++;
} while (i <= 3);
// Menu system — always show menu at least once
int choice = 0;
do {
print('\n--- Menu ---');
print('1. View Profile');
print('2. Settings');
print('3. Logout');
choice = 3; // simulate user choosing 3
print('Selected: $choice');
} while (choice != 3);
print('Logged out.');
// Condition false from start — body still runs once
int x = 10;
do {
print('This runs once even though x > 5');
} while (x < 5);
}
Output:i = 1
i = 2
i = 3
--- Menu ---
...
Selected: 3
Logged out.
This runs once even though x > 5
🧠 Quiz
1. How many times will a do-while loop run if its condition is immediately false?
- A) 0 times
- B) 1 time ✅
- C) Infinite
- D) Error
Summary
The do-while loop always executes its body at least once before checking the condition. Use it for menus, input validation prompts, or any scenario where the first execution is mandatory.