Do-While Loop
The do-while loop is a special type of loop that guarantees the code block will execute at least once, even if the condition is false from the beginning. Think of it like trying a new restaurant - you'll definitely go there once, and then decide if you want to go back based on your experience!
Syntax
do {
// Code to be executed
} while (condition);
The key difference from a regular while loop is that the condition is checked after the code block executes, not before.
How It Works
- Execute the code block first
- Check the condition
- If the condition is
true, repeat from step 1 - If the condition is
false, exit the loop
Basic Example
void main() {
int count = 1;
do {
print('Count: $count');
count++;
} while (count <= 3);
}
Output:
Count: 1
Count: 2
Count: 3
Key Difference: Do-While vs While
Let's see what happens when the condition is false from the start:
Do-While Loop
void main() {
int number = 10;
do {
print('This will print at least once: $number');
} while (number < 5); // false condition
}
Output:
This will print at least once: 10
Regular While Loop
void main() {
int number = 10;
while (number < 5) { // false condition
print('This will never print: $number');
}
}
Output: (nothing prints)
Practical Example: User Input Validation
import 'dart:io';
void main() {
String? userInput;
do {
print('Enter "yes" to continue or "no" to exit:');
userInput = stdin.readLineSync();
if (userInput != 'yes' && userInput != 'no') {
print('Invalid input! Please try again.');
}
} while (userInput != 'yes' && userInput != 'no');
print('You entered: $userInput');
}
This ensures the user is prompted at least once and keeps asking until they provide valid input.
Common Use Cases
| Use Case | Description |
|---|---|
| Menu Systems | Show menu at least once, repeat based on user choice |
| Input Validation | Ask for input, validate, and re-ask if invalid |
| Game Loops | Play game at least once, ask if player wants to continue |
| Data Processing | Process data once, check if more data exists |
Important Notes
- Always ensure your condition can eventually become
falseto avoid infinite loops - The semicolon (
;) after the while condition is required - Use do-while when you need to execute code at least once, regardless of the initial condition
The do-while loop is perfect when you want to guarantee that something happens at least once - like giving everyone a chance to try something before deciding if they want to continue!