Watch the video (10 min)
On this page23 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is a while Loop?
  5. 2. Writing a while Loop
  6. 3. How a while Loop Runs
  7. 4. The Loop Must Make Progress
  8. 5. Infinite Loops
  9. 6. When You Don't Know How Many Rounds
  10. 7. Repeated Halving
  11. 8. The do-while Loop
  12. 9. do-while Always Runs at Least Once
  13. 10. Choosing Between for, while, and do-while
  14. 11. A Real-World Example
  15. Code Examples
  16. Common Beginner Mistakes
  17. Best Practices
  18. Mini Challenge
  19. Practice Questions
  20. Practice Answers
  21. Quick Revision
  22. Key Takeaways
  23. What's Next?

Lecture 28 — while & do-while

Category5 — Control Flow
Lecture028 of 140
Estimated video length10 min
TargetDart 3.12.2
LevelBeginner

A for loop 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. A while loop 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, int and double, and string interpolation
  • comparison operators, +=, ~/, and ++
  • if and if-else (Lectures 022–023)
  • the for loop and its three parts (Lecture 026)

Connection With Previous Lectures

In Lecture 026, every for loop had its end written into it:

dart
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 while loop and trace how it runs
  • Explain why a while loop 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-while loop and explain why it always runs at least once
  • Choose between for, while, and do-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:

dart
void main() {
  var count = 1;
  while (count <= 3) {
    print('Round $count');
    count++;
  }
  print('Done');
}
output
Round 1
Round 2
Round 3
Done

The 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.

Checkcountcount <= 3Action
11trueprint Round 1, count becomes 2
22trueprint Round 2, count becomes 3
33trueprint Round 3, count becomes 4
44falseleave the loop, print Done

The condition is checked first, so if it is false from the start, the body never runs:

dart
void main() {
  var count = 10;
  while (count <= 3) {
    print('Round $count');
    count++;
  }
  print('Done');
}
output
Done

4. 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:

dart
void main() {
  var balance = 1000;
  while (balance >= 300) {
    balance -= 300;
    print('Withdrew 300, balance: $balance');
  }
}
output
Withdrew 300, balance: 700
Withdrew 300, balance: 400
Withdrew 300, balance: 100

At 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:

dart
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);
}
output
1

Dart 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:

dart
void main() {
  var savings = 5000;
  var months = 0;
  while (savings < 20000) {
    savings += 1500;
    months++;
  }
  print('Months needed: $months');
  print('Savings: $savings');
}
output
Months needed: 10
Savings: 20000

We 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?

dart
void main() {
  var number = 100;
  var steps = 0;
  while (number > 1) {
    number = number ~/ 2;
    steps++;
    print('Step $steps: $number');
  }
}
output
Step 1: 50
Step 2: 25
Step 3: 12
Step 4: 6
Step 5: 3
Step 6: 1

The 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:

dart
void main() {
  var count = 1;
  do {
    print('Round $count');
    count++;
  } while (count <= 3);
}
output
Round 1
Round 2
Round 3

Note 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:

dart
void main() {
  var count = 10;
  do {
    print('Round $count');
    count++;
  } while (count <= 3);
}
output
Round 10

This is useful when the first round must always happen. Counting the digits of a number is a good case: even 0 has one digit.

dart
void main() {
  var number = 0;
  var digits = 0;
  do {
    digits++;
    number = number ~/ 10;
  } while (number > 0);
  print('Digits: $digits');
}
output
Digits: 1

With 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:

UseWhenExample
forthe number of rounds is known before the loop startsprint 1 to 10, 12 months
whileyou repeat until something happens, and it may happen at oncesaving until a target
do-whilelike while, but the first round must always runcounting 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?

dart
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.');
}
output
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

dart
void main() {
  var number = 1;
  while (number <= 5) {
    print(number);
    number++;
  }
}
output
1
2
3
4
5

Example 2 — Countdown

dart
void main() {
  var seconds = 3;
  while (seconds > 0) {
    print('$seconds...');
    seconds--;
  }
  print('Go!');
}
output
3...
2...
1...
Go!

Example 3 — Even Numbers

dart
void main() {
  var number = 2;
  while (number <= 10) {
    print(number);
    number += 2;
  }
}
output
2
4
6
8
10

Example 4 — A Running Sum

dart
void main() {
  var number = 1;
  var sum = 0;
  while (number <= 5) {
    sum += number;
    number++;
  }
  print('Sum: $sum');
}
output
Sum: 15

Example 5 — Doubling Until a Limit

dart
void main() {
  var value = 1;
  while (value < 100) {
    print(value);
    value *= 2;
  }
}
output
1
2
4
8
16
32
64

Example 6 — do-while Countdown

dart
void main() {
  var count = 3;
  do {
    print('Count: $count');
    count--;
  } while (count > 0);
}
output
Count: 3
Count: 2
Count: 1

Example 7 — Student Marks

Ali scores 40 and improves by 8 marks on every test. How many tests until he reaches 75?

dart
void main() {
  var marks = 40;
  var tests = 0;
  while (marks < 75) {
    marks += 8;
    tests++;
  }
  print('Tests needed: $tests');
  print('Marks: $marks');
}
output
Tests needed: 5
Marks: 80

How it works

  1. After 4 tests, marks is 72 — still below 75, so the loop runs again.
  2. After test 5, marks is 80, the condition is false, and the loop ends.
  3. The final mark overshoots the target; a while loop 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?

dart
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');
}
output
Cars bought: 5
Money left: 100

How it works

  1. The condition asks "can he still afford one?" before every purchase.
  2. After 5 cars, 100 is left, which is less than 180, so the loop stops.

Example 9 — Bank Balance

dart
void main() {
  var balance = 2000;
  var month = 0;
  while (balance > 0) {
    month++;
    balance -= 450;
    if (balance < 0) {
      balance = 0;
    }
    print('Month $month: $balance');
  }
}
output
Month 1: 1550
Month 2: 1100
Month 3: 650
Month 4: 200
Month 5: 0

How it works

  1. Each round spends 450, and the if stops the balance going negative.
  2. Once balance is 0, balance > 0 is false and the loop ends.

Example 10 — Cooling Tea

Tea starts at 90 degrees and loses 7 degrees a minute. It is drinkable below 60.

dart
void main() {
  var temperature = 90;
  var minutes = 0;
  while (temperature >= 60) {
    temperature -= 7;
    minutes++;
  }
  print('Ready after $minutes minutes at $temperature degrees.');
}
output
Ready after 5 minutes at 55 degrees.

How it works

  1. 90 → 83 → 76 → 69 → 62 → 55: five rounds.
  2. At 55, temperature >= 60 is false, so the loop ends.

Common Beginner Mistakes

1. Forgetting to update the loop variable

dart
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 (...)

dart
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

dart
void main() {
  var count = 1;
  do {
    count++;
  } while (count <= 3) // ✗
}
output
Error: Expected ';' after this.
  } while (count <= 3) // ✗
                     ^

4. Declaring the variable inside a do body

dart
void main() {
  do {
    var count = 1;
    count++;
  } while (count <= 3); // ✗
}
output
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

dart
void main() {
  var count = 1;
  while (count > 5) {
    print(count);
    count++;
  }
  print('Finished');
}
output
Finished

The loop body never ran — 1 > 5 is false immediately. The intended condition was count <= 5.


Best Practices

  • Use for when the number of rounds is known; use while when you repeat until something happens.
  • Use do-while only when the first round must always run.
  • Before running a new while loop, find the line that moves the condition towards false.
  • 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:

output
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
dart
void main() {
  var battery = 100;
  var hours = 0;
  while (battery >= 20) {
    battery -= 15;
    hours++;
    print('Hour $hours: $battery%');
  }
  print('Charge after $hours hours.');
}
output
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

  1. The loop runs while the battery is 20% or more.
  2. After hour 6 the battery is 10, the condition is false, and the loop ends.

Practice Questions

Work through these in order — they run from beginner to application to challenge.

Beginner

  1. Use a while loop to print the numbers 1 to 4, each on its own line.
  2. Use a while loop to print 10, 8, 6, 4, 2.
  3. Use a do-while loop to print Hello three times.

Application

  1. Use a while loop to add up the numbers 1 to 10 and print Sum: 55.

  2. Sara has 3000 rupees and saves 700 a month. Print how many months until she has at least 7000, and her savings at that point.

  3. Start at 1 and keep multiplying by 3 while the value is below 200. Print each value.

  4. Without running it, how many times does Hi print? Then explain why.

    dart
    void main() {
      var x = 5;
      do {
        print('Hi');
        x++;
      } while (x < 3);
    }
  5. This program never finishes. Fix it so it prints 1, 2, 3:

    dart
    void main() {
      var n = 1;
      // while (n <= 3) {
      //   print(n);
      // }
    }

Challenge

  1. Halve 1000 with ~/ until it is 1 or less. Print only the final number of steps.
  2. Use a do-while loop to count the digits of 45210, and print Digits: 5.

Practice Answers

Question 1 — Solution

dart
void main() {
  var n = 1;
  while (n <= 4) {
    print(n);
    n++;
  }
}
output
1
2
3
4

Question 2 — Solution

dart
void main() {
  var n = 10;
  while (n >= 2) {
    print(n);
    n -= 2;
  }
}
output
10
8
6
4
2

Question 3 — Solution

dart
void main() {
  var times = 0;
  do {
    print('Hello');
    times++;
  } while (times < 3);
}
output
Hello
Hello
Hello

Question 4 — Solution

dart
void main() {
  var n = 1;
  var sum = 0;
  while (n <= 10) {
    sum += n;
    n++;
  }
  print('Sum: $sum');
}
output
Sum: 55

Question 5 — Solution

dart
void main() {
  var savings = 3000;
  var months = 0;
  while (savings < 7000) {
    savings += 700;
    months++;
  }
  print('Months: $months');
  print('Savings: $savings');
}
output
Months: 6
Savings: 7200

Question 6 — Solution

dart
void main() {
  var value = 1;
  while (value < 200) {
    print(value);
    value *= 3;
  }
}
output
1
3
9
27
81

Question 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.

output
Hi

Question 8 — Solution

Add n++ so the condition eventually becomes false:

dart
void main() {
  var n = 1;
  while (n <= 3) {
    print(n);
    n++;
  }
}
output
1
2
3

Question 9 — Solution

dart
void main() {
  var number = 1000;
  var steps = 0;
  while (number > 1) {
    number = number ~/ 2;
    steps++;
  }
  print('Steps: $steps');
}
output
Steps: 9

Question 10 — Solution

dart
void main() {
  var number = 45210;
  var digits = 0;
  do {
    digits++;
    number = number ~/ 10;
  } while (number > 0);
  print('Digits: $digits');
}
output
Digits: 5

Quick Revision

  1. When does a while loop check its condition?
  2. Can a while loop run zero times? Can a do-while loop?
  3. What is an infinite loop, and how do you stop one that is running?
  4. Which punctuation does do-while need that while does not?
  5. Why must a variable used in a do-while condition be declared before do?
  6. When is while a better choice than for?

Key Takeaways

  • A while loop repeats its body as long as its condition is true.
  • The condition is checked before every round, so a while loop 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.
  • while shines when the number of rounds is the unknown: saving to a target, halving, cooling.
  • do-while checks after the body, so it always runs at least once, and ends with ;.
  • Use for for "repeat N times", while for "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.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.