Feature | While Loop | Do...While Loop |
Loop Entry | Condition is checked before entering the loop | Code block is executed before checking the condition |
Execution Order | Condition is evaluated before execution | Code block is executed before condition check |
Guarantee | May execute zero times if condition is false initially | Executes at least once, then checks condition |
Syntax | while (condition) { /* code */ } | do { /* code */ } while (condition); |
Usage Scenario | Preferable when the condition may be false initially | Suitable when at least one execution is required before condition check |
Loop Continuation | Continues executing as long as the condition is true | Continues executing as long as the condition is true, but at least one execution is guaranteed |
Exit Condition | Condition is checked before every iteration | Condition is checked after every iteration |
Example of While Loop:
void main() {
var i = 1;
while (i <= 5) {
print(i);
i++;
}
}
Example Do While Loop:
void main() {
var i = 1;
do {
print(i);
i++;
} while (i <= 5);
}