On this page23 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is a while Loop?
- 2. Writing a while Loop
- 3. How a while Loop Runs
- 4. The Loop Must Make Progress
- 5. Infinite Loops
- 6. When You Don't Know How Many Rounds
- 7. Repeated Halving
- 8. The do-while Loop
- 9. do-while Always Runs at Least Once
- 10. Choosing Between for, while, and do-while
- 11. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 28 — while & do-while
| Category | 5 — Control Flow |
| Lecture | 028 of 140 |
| Estimated video length | 10 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
A
forloop works when you know how many times to repeat. But "how many months until Ali saves enough?" is the very thing you want to find out. Awhileloop repeats until a condition stops being true — however many rounds that takes.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways
Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.
Prerequisites
Students should already understand, from Lectures 001–027:
- variables,
intanddouble, and string interpolation - comparison operators,
+=,~/, and++ ifandif-else(Lectures 022–023)- the
forloop and its three parts (Lecture 026)
Connection With Previous Lectures
In Lecture 026, every for loop had its end written into it:
for (var month = 1; month <= 12; month++) {
// ...
}Twelve rounds, decided before the loop starts. Now try this: Ali has 5000 rupees and saves
1500 every month. How many months until he reaches 20000? You cannot write the
number of rounds into the loop — that number is the answer you are looking for. You need a
loop that keeps going as long as he has not reached the target, and stops by itself.
Learning Objectives
By the end of this lecture you will be able to:
- Write a
whileloop and trace how it runs - Explain why a
whileloop may run zero times - Update the loop variable so the loop finishes
- Recognize an infinite loop and stop a program that is stuck in one
- Solve problems whose number of rounds is not known in advance
- Write a
do-whileloop and explain why it always runs at least once - Choose between
for,while, anddo-while - Recognize the common mistakes and error messages around these loops
1. What Is a while Loop?
A while loop repeats a block of code as long as a condition is true. Before every
round, Dart checks the condition. When it becomes false, the loop ends.
Analogy — filling a bucket from a tap. You don't count jugs in advance; you keep pouring while the bucket is not full, and stop the moment it is.
2. Writing a while Loop
The condition goes in parentheses after while; the code to repeat goes in braces:
void main() {
var count = 1;
while (count <= 3) {
print('Round $count');
count++;
}
print('Done');
}Round 1
Round 2
Round 3
DoneThe three parts of a for loop are still here, just spread out: the start (var count = 1)
before the loop, the condition inside while (...), and the step (count++) at the end of
the body.
3. How a while Loop Runs
Dart repeats one cycle: check the condition → run the body → check again.
| Check | count | count <= 3 | Action |
|---|---|---|---|
| 1 | 1 | true | print Round 1, count becomes 2 |
| 2 | 2 | true | print Round 2, count becomes 3 |
| 3 | 3 | true | print Round 3, count becomes 4 |
| 4 | 4 | false | leave the loop, print Done |
The condition is checked first, so if it is false from the start, the body never runs:
void main() {
var count = 10;
while (count <= 3) {
print('Round $count');
count++;
}
print('Done');
}Done4. The Loop Must Make Progress
Something inside the body must move the condition towards false. Here, balance drops
with every withdrawal, so the loop is guaranteed to end:
void main() {
var balance = 1000;
while (balance >= 300) {
balance -= 300;
print('Withdrew 300, balance: $balance');
}
}Withdrew 300, balance: 700
Withdrew 300, balance: 400
Withdrew 300, balance: 100At 100, balance >= 300 is false, and the loop stops before the balance can go below zero.
5. Infinite Loops
If nothing in the body changes the condition, it stays true forever. This is an
infinite loop — the program never finishes. Both loops below are commented out so this
file is safe to run:
void main() {
var count = 1;
// while (count <= 3) {
// print('Round $count'); // count never changes — prints forever
// }
// while (true) {
// print('Hello'); // true is always true — prints forever
// }
print(count);
}1Dart reports no error: an infinite loop is legal code with a logic mistake. If you ever run
one by accident, press Ctrl + C in the terminal (or the stop button in your editor) to
end the program. while (true) does have real uses, together with break — we will study
that in Lecture 029.
6. When You Don't Know How Many Rounds
Here is Ali's savings question from the start. The loop counts the months for us:
void main() {
var savings = 5000;
var months = 0;
while (savings < 20000) {
savings += 1500;
months++;
}
print('Months needed: $months');
print('Savings: $savings');
}Months needed: 10
Savings: 20000We never told the loop "10". It kept saving while the target was not reached, and months
recorded how many rounds that took. Change the target and the answer updates by itself.
7. Repeated Halving
Another classic: how many times can you halve 100 (dropping the remainder with ~/)
before it reaches 1?
void main() {
var number = 100;
var steps = 0;
while (number > 1) {
number = number ~/ 2;
steps++;
print('Step $steps: $number');
}
}Step 1: 50
Step 2: 25
Step 3: 12
Step 4: 6
Step 5: 3
Step 6: 1The step count depends on the starting value — exactly the kind of problem while is for.
8. The do-while Loop
A do-while loop puts the condition after the body. Dart runs the body first, then
checks whether to go again:
void main() {
var count = 1;
do {
print('Round $count');
count++;
} while (count <= 3);
}Round 1
Round 2
Round 3Note the semicolon after while (count <= 3) — a do-while loop ends with one, a
while loop does not.
9. do-while Always Runs at Least Once
Because the check comes last, the body runs once even when the condition is false from the
start. Compare with section 3:
void main() {
var count = 10;
do {
print('Round $count');
count++;
} while (count <= 3);
}Round 10This is useful when the first round must always happen. Counting the digits of a number is
a good case: even 0 has one digit.
void main() {
var number = 0;
var digits = 0;
do {
digits++;
number = number ~/ 10;
} while (number > 0);
print('Digits: $digits');
}Digits: 1With a plain while (number > 0), the body would never run for 0, and the answer would be
0 digits — wrong.
10. Choosing Between for, while, and do-while
Any for loop can be rewritten as a while loop, so the choice is about what reads best:
| Use | When | Example |
|---|---|---|
for | the number of rounds is known before the loop starts | print 1 to 10, 12 months |
while | you repeat until something happens, and it may happen at once | saving until a target |
do-while | like while, but the first round must always run | counting digits |
A good test: if you can say "repeat N times", use for. If you can only say "repeat
until ...", use while.
11. A Real-World Example
Sara deposits 10000 rupees in an account that earns 8% interest a year. How many years
until her money doubles?
void main() {
var balance = 10000.0;
var target = balance * 2;
var years = 0;
while (balance < target) {
balance += balance * 0.08;
years++;
print('Year $years: ${balance.toStringAsFixed(2)}');
}
print('Doubled after $years years.');
}Year 1: 10800.00
Year 2: 11664.00
Year 3: 12597.12
Year 4: 13604.89
Year 5: 14693.28
Year 6: 15868.74
Year 7: 17138.24
Year 8: 18509.30
Year 9: 19990.05
Year 10: 21589.25
Doubled after 10 years.balance grows by a different amount each year, so nobody could know "10" in advance. The
condition balance < target does the deciding, balance makes progress every round, and
years counts the rounds.
Code Examples
Example 1 — Counting Up
void main() {
var number = 1;
while (number <= 5) {
print(number);
number++;
}
}1
2
3
4
5Example 2 — Countdown
void main() {
var seconds = 3;
while (seconds > 0) {
print('$seconds...');
seconds--;
}
print('Go!');
}3...
2...
1...
Go!Example 3 — Even Numbers
void main() {
var number = 2;
while (number <= 10) {
print(number);
number += 2;
}
}2
4
6
8
10Example 4 — A Running Sum
void main() {
var number = 1;
var sum = 0;
while (number <= 5) {
sum += number;
number++;
}
print('Sum: $sum');
}Sum: 15Example 5 — Doubling Until a Limit
void main() {
var value = 1;
while (value < 100) {
print(value);
value *= 2;
}
}1
2
4
8
16
32
64Example 6 — do-while Countdown
void main() {
var count = 3;
do {
print('Count: $count');
count--;
} while (count > 0);
}Count: 3
Count: 2
Count: 1Example 7 — Student Marks
Ali scores 40 and improves by 8 marks on every test. How many tests until he reaches 75?
void main() {
var marks = 40;
var tests = 0;
while (marks < 75) {
marks += 8;
tests++;
}
print('Tests needed: $tests');
print('Marks: $marks');
}Tests needed: 5
Marks: 80How it works
- After 4 tests,
marksis72— still below75, so the loop runs again. - After test 5,
marksis80, the condition isfalse, and the loop ends. - The final mark overshoots the target; a
whileloop stops at the first round that reaches it.
Example 8 — Shopping Budget
Zayan has 1000 rupees. Each toy car costs 180. How many can he buy?
void main() {
var money = 1000;
var price = 180;
var cars = 0;
while (money >= price) {
money -= price;
cars++;
}
print('Cars bought: $cars');
print('Money left: $money');
}Cars bought: 5
Money left: 100How it works
- The condition asks "can he still afford one?" before every purchase.
- After 5 cars,
100is left, which is less than180, so the loop stops.
Example 9 — Bank Balance
void main() {
var balance = 2000;
var month = 0;
while (balance > 0) {
month++;
balance -= 450;
if (balance < 0) {
balance = 0;
}
print('Month $month: $balance');
}
}Month 1: 1550
Month 2: 1100
Month 3: 650
Month 4: 200
Month 5: 0How it works
- Each round spends
450, and theifstops the balance going negative. - Once
balanceis0,balance > 0isfalseand the loop ends.
Example 10 — Cooling Tea
Tea starts at 90 degrees and loses 7 degrees a minute. It is drinkable below 60.
void main() {
var temperature = 90;
var minutes = 0;
while (temperature >= 60) {
temperature -= 7;
minutes++;
}
print('Ready after $minutes minutes at $temperature degrees.');
}Ready after 5 minutes at 55 degrees.How it works
90 → 83 → 76 → 69 → 62 → 55: five rounds.- At
55,temperature >= 60isfalse, so the loop ends.
Common Beginner Mistakes
1. Forgetting to update the loop variable
void main() {
var count = 1;
// while (count <= 3) { // ✗ count never changes — infinite loop
// print(count);
// }
print(count);
}No error is reported — the program just never ends. Make sure the body changes something the condition depends on.
2. A semicolon right after while (...)
void main() {
var count = 1;
// while (count <= 3); { // ✗ the ; is an empty loop body
// print(count);
// count++;
// }
print(count);
}The ; becomes the whole body, so the empty loop spins forever and the braces are never
reached. A while line never ends in ;.
3. Forgetting the semicolon after do-while
void main() {
var count = 1;
do {
count++;
} while (count <= 3) // ✗
}Error: Expected ';' after this.
} while (count <= 3) // ✗
^4. Declaring the variable inside a do body
void main() {
do {
var count = 1;
count++;
} while (count <= 3); // ✗
}Error: Undefined name 'count'.
} while (count <= 3); // ✗
^^^^^A variable declared inside the braces does not exist in the condition. Declare it before
do.
5. A condition that is false from the start
void main() {
var count = 1;
while (count > 5) {
print(count);
count++;
}
print('Finished');
}FinishedThe loop body never ran — 1 > 5 is false immediately. The intended condition was
count <= 5.
Best Practices
- Use
forwhen the number of rounds is known; usewhilewhen you repeat until something happens. - Use
do-whileonly when the first round must always run. - Before running a new
whileloop, find the line that moves the condition towardsfalse. - Write conditions with
<,>,<=, or>=rather than!=, so an overshoot still ends the loop. - Declare loop variables before the loop and give them clear names:
months,balance. - Keep infinite-loop examples commented out, and remember Ctrl + C stops a stuck program.
Mini Challenge
Ali's phone battery is at 100% and drops 15% every hour. Use a while loop to print the
battery level each hour until it falls below 20%, then print how many hours passed.
Your program should print exactly:
Hour 1: 85%
Hour 2: 70%
Hour 3: 55%
Hour 4: 40%
Hour 5: 25%
Hour 6: 10%
Charge after 6 hours.Try it yourself before opening the solution.
Show solution
void main() {
var battery = 100;
var hours = 0;
while (battery >= 20) {
battery -= 15;
hours++;
print('Hour $hours: $battery%');
}
print('Charge after $hours hours.');
}Hour 1: 85%
Hour 2: 70%
Hour 3: 55%
Hour 4: 40%
Hour 5: 25%
Hour 6: 10%
Charge after 6 hours.How it works
- The loop runs while the battery is
20%or more. - After hour 6 the battery is
10, the condition isfalse, and the loop ends.
Practice Questions
Work through these in order — they run from beginner to application to challenge.
Beginner
- Use a
whileloop to print the numbers1to4, each on its own line. - Use a
whileloop to print10,8,6,4,2. - Use a
do-whileloop to printHellothree times.
Application
-
Use a
whileloop to add up the numbers1to10and printSum: 55. -
Sara has
3000rupees and saves700a month. Print how many months until she has at least7000, and her savings at that point. -
Start at
1and keep multiplying by3while the value is below200. Print each value. -
Without running it, how many times does
Hiprint? Then explain why.void main() { var x = 5; do { print('Hi'); x++; } while (x < 3); } -
This program never finishes. Fix it so it prints
1,2,3:void main() { var n = 1; // while (n <= 3) { // print(n); // } }
Challenge
- Halve
1000with~/until it is1or less. Print only the final number of steps. - Use a
do-whileloop to count the digits of45210, and printDigits: 5.
Practice Answers
Question 1 — Solution
void main() {
var n = 1;
while (n <= 4) {
print(n);
n++;
}
}1
2
3
4Question 2 — Solution
void main() {
var n = 10;
while (n >= 2) {
print(n);
n -= 2;
}
}10
8
6
4
2Question 3 — Solution
void main() {
var times = 0;
do {
print('Hello');
times++;
} while (times < 3);
}Hello
Hello
HelloQuestion 4 — Solution
void main() {
var n = 1;
var sum = 0;
while (n <= 10) {
sum += n;
n++;
}
print('Sum: $sum');
}Sum: 55Question 5 — Solution
void main() {
var savings = 3000;
var months = 0;
while (savings < 7000) {
savings += 700;
months++;
}
print('Months: $months');
print('Savings: $savings');
}Months: 6
Savings: 7200Question 6 — Solution
void main() {
var value = 1;
while (value < 200) {
print(value);
value *= 3;
}
}1
3
9
27
81Question 7 — Solution
Hi prints once. A do-while loop runs its body before checking the condition. After
the first round, x is 6, 6 < 3 is false, and the loop ends.
HiQuestion 8 — Solution
Add n++ so the condition eventually becomes false:
void main() {
var n = 1;
while (n <= 3) {
print(n);
n++;
}
}1
2
3Question 9 — Solution
void main() {
var number = 1000;
var steps = 0;
while (number > 1) {
number = number ~/ 2;
steps++;
}
print('Steps: $steps');
}Steps: 9Question 10 — Solution
void main() {
var number = 45210;
var digits = 0;
do {
digits++;
number = number ~/ 10;
} while (number > 0);
print('Digits: $digits');
}Digits: 5Quick Revision
- When does a
whileloop check its condition? - Can a
whileloop run zero times? Can ado-whileloop? - What is an infinite loop, and how do you stop one that is running?
- Which punctuation does
do-whileneed thatwhiledoes not? - Why must a variable used in a
do-whilecondition be declared beforedo? - When is
whilea better choice thanfor?
Key Takeaways
- A
whileloop repeats its body as long as its condition istrue. - The condition is checked before every round, so a
whileloop can run zero times. - The body must move the condition towards
false; otherwise the loop is infinite. - An infinite loop is not an error — stop a stuck program with Ctrl + C.
whileshines when the number of rounds is the unknown: saving to a target, halving, cooling.do-whilechecks after the body, so it always runs at least once, and ends with;.- Use
forfor "repeat N times",whilefor "repeat until".
What's Next?
Lecture 029 — break & continue. So far a loop ends only when its condition turns
false, and every round runs the whole body. Sometimes you want to leave a loop the moment
you find what you are looking for, or skip just one round. Next we will learn break and
continue — and finally put while (true) to good use.