On this page12 sections
Lecture 021: while vs do-while
| Day | 8: Loops |
| Lecture | 021 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
A
forloop is great when you know how many rounds you need. But "keep saving until I reach Rs 50,000" or "keep asking for the PIN until it's right" don't have a fixed count.whileanddo-whilerepeat as long as a condition holds.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lecture 020 (for loops and ++ / +=).
Learning Objectives
- Write a
whileloop - Write a
do-whileloop - Explain the one difference between them
- Avoid infinite loops
- Choose between
for,whileanddo-while
1. The while Loop
while (condition) {
// repeated while condition is true
}var count = 1;
while (count <= 3) {
print('while: $count');
count++;
}Output
while: 1
while: 2
while: 3The condition is checked before every round. Something inside the loop must eventually make
it false (here, count++).
2. The do-while Loop
do {
// repeated
} while (condition);var n = 1;
do {
print('do-while: $n');
n++;
} while (n <= 3);The output is the same: do-while: 1, 2, 3. Note the ; after the condition.
3. The Difference
while checks first. do-while runs the body first, then checks. So a do-while always
runs at least once:
var a = 10;
while (a < 5) {
print('while body (never runs)');
}
var b = 10;
do {
print('do-while body runs once even though $b < 5 is false');
} while (b < 5);Output
do-while body runs once even though 10 < 5 is falsewhile | do-while | |
|---|---|---|
| Condition checked | before each round | after each round |
| Minimum runs | 0 | 1 |
| Typical use | "repeat while something is true" | "do it, then decide whether to repeat" (menus, asking for input) |
4. Loops Without a Fixed Count
var money = 1000;
var days = 0;
while (money > 0) {
money -= 300;
days++;
}
print('Money ran out after $days days (left: $money)');
// Money ran out after 4 days (left: -200)
var number = 4821;
var digits = 0;
while (number > 0) {
number = number ~/ 10; // drop the last digit
digits++;
}
print('Digits: $digits'); // Digits: 4Neither loop knows in advance how many rounds it needs, which is exactly what while is for.
5. Which Loop?
| You know… | Use |
|---|---|
| how many times (or you're going through a list) | for / for-in |
| a condition, and it might be false from the start | while |
| the body must run at least once | do-while |
Code Examples
Example 1: PIN Attempts and a Savings Goal
void main() {
// Pretend these are the PINs a user types, one attempt at a time
var attempts = ['1111', '2580', '4321'];
var correctPin = '4321';
var tries = 0;
var entered = '';
do {
entered = attempts[tries];
tries++;
print('Attempt $tries: $entered');
} while (entered != correctPin && tries < 3);
if (entered == correctPin) {
print('Unlocked after $tries attempts');
} else {
print('Card blocked');
}
var savings = 0;
var month = 0;
while (savings < 50000) {
savings += 12000;
month++;
}
print('Goal reached in month $month with Rs $savings');
}Output
Attempt 1: 1111
Attempt 2: 2580
Attempt 3: 4321
Unlocked after 3 attempts
Goal reached in month 5 with Rs 60000The PIN check is a do-while because the user must type at least once. The loop stops when the
PIN is right or after 3 tries, whichever comes first.
Common Beginner Mistakes
1. The infinite loop
var i = 0;
while (i < 3) {
print(i);
}i never changes, so i < 3 is always true. The program prints 0 forever and never finishes.
Stop it with the stop button in DartPad or your IDE, or Ctrl + C in a terminal. Fix it by
adding i++; inside the loop.
2. Forgetting the ; after do-while
} while (n <= 2)Error: Expected ';' after this.3. Off-by-one conditions: while (count < 3) runs for 1 and 2; while (count <= 3) also
runs for 3. Read your condition aloud with the first and last values.
4. Using while for a simple count: for (var i = 0; i < 10; i++) keeps the start, the
condition and the step in one place, so it's harder to forget the step.
Practice Questions
- How many times does the body run in
var x = 5; while (x < 3) { x++; }? - And in
var y = 5; do { y++; } while (y < 3);? - Write a
whileloop that prints 10, 8, 6, 4, 2. - Why does
while (true) { print('hi'); }never stop? - You're showing a menu that must appear at least once.
whileordo-while?
Practice Answers
- 0 times. The condition is false from the start.
- Once.
do-whileruns before checking.
var n = 10;
while (n >= 2) {
print(n);
n -= 2;
}- The condition is always
true, and nothing inside ends the loop. (Lecture 023 shows howbreakcan.) do-while.
Key Takeaways
whilechecks before each round and may run zero times.do-whilechecks after each round and always runs at least once; it ends with;.- Something inside the loop must eventually make the condition false.
forfor counts and lists;while/do-whilefor "until something happens".