Watch the video (8 min)
On this page24 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. Why Stop a Loop Early?
  5. 2. break Leaves the Loop
  6. 3. After break, the Program Continues Below the Loop
  7. 4. continue Skips One Round
  8. 5. break vs continue
  9. 6. break and continue in a for-in Loop
  10. 7. break and continue in a while Loop
  11. 8. while (true) With break
  12. 9. break in Nested Loops
  13. 10. Labels: Leaving the Outer Loop
  14. 11. continue With a Label
  15. 12. A Real-World Example
  16. Code Examples
  17. Common Beginner Mistakes
  18. Best Practices
  19. Mini Challenge
  20. Practice Questions
  21. Practice Answers
  22. Quick Revision
  23. Key Takeaways
  24. What's Next?

Lecture 29 — break & continue

Category5 — Control Flow
Lecture029 of 140
Estimated video length8 min
TargetDart 3.12.2
LevelBeginner

A loop so far runs every round until its condition turns false. break lets you leave a loop early, and continue lets you skip one round and carry on with the next.

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 004–028:

  • variables, string interpolation, and the operators ++, +=, %, ==, &&
  • if and if-else (Lectures 022–023)
  • for loops (Lecture 026)
  • for-in loops over a list written in square brackets, such as [80, 45, 90] (Lecture 027)
  • while and do-while (Lecture 028)

Connection With Previous Lectures

Suppose Sara wants the first failing mark among 80, 92, 45, 70, 38. A for-in loop can find 45 — but then it keeps going and reports 38 too. And to ignore some values, the whole loop body has to sit inside an if. A loop needs a way to say "stop now" and "skip this one".


Learning Objectives

By the end of this lecture you will be able to:

  • Explain what break and continue do
  • Use break to leave a loop as soon as the answer is found
  • Use continue to skip the rest of one round
  • Use both in for, for-in, and while loops
  • Write a while (true) loop that ends with break
  • Predict how break behaves inside nested loops
  • Use a label such as outer: to leave or skip an outer loop
  • Recognize the error messages Dart gives for misplaced break and continue

1. Why Stop a Loop Early?

Many loops are searches: they check values one by one until they find the right one. After that, the remaining rounds are wasted work — and may even give wrong answers.

Analogy — you are looking for your keys in a row of drawers. When you find them in the second drawer, you stop (break). If a drawer is locked, you skip it and open the next one (continue).


2. break Leaves the Loop

break ends the loop immediately, no matter what its condition says.

dart
void main() {
  for (int i = 1; i <= 10; i++) {
    if (i == 4) {
      break;
    }
    print(i);
  }
}
output
1
2
3

The loop was written to count to 10, but when i reaches 4, break ends it. print(i) for 4 never runs.


3. After break, the Program Continues Below the Loop

break ends only the loop, not the program. Execution jumps to the first line after the loop's closing brace.

dart
void main() {
  for (int i = 1; i <= 10; i++) {
    if (i == 3) {
      break;
    }
    print('Round $i');
  }
  print('Loop finished');
}
output
Round 1
Round 2
Loop finished

4. continue Skips One Round

continue stops the current round and jumps straight to the next one. The loop itself keeps going.

dart
void main() {
  for (int i = 1; i <= 5; i++) {
    if (i == 3) {
      continue;
    }
    print(i);
  }
}
output
1
2
4
5

When i is 3, continue skips print(i). In a for loop, the update i++ still runs, so the next round has i equal to 4.


5. break vs continue

breakcontinue
Stops the current round?yesyes
Runs more rounds?no — the loop is overyes — goes to the next round
Typical use"found it, stop searching""ignore this value, keep going"

6. break and continue in a for-in Loop

They work the same way when the loop walks through a list. This solves Sara's problem from the start of the lecture:

dart
void main() {
  for (int mark in [80, 92, 45, 70, 38]) {
    if (mark < 50) {
      print('First failing mark: $mark');
      break;
    }
  }
}
output
First failing mark: 45

38 is never checked — the loop stopped at 45.


7. break and continue in a while Loop

In a while loop, break works exactly as before:

dart
void main() {
  int balance = 100;
  while (balance > 0) {
    balance -= 30;
    if (balance < 50) {
      break;
    }
    print('Balance: $balance');
  }
  print('Stopped at $balance');
}
output
Balance: 70
Stopped at 40

continue needs care. A while loop has no separate update part, so continue jumps straight back to the condition. Change the counter before continue, or the loop never moves on:

dart
void main() {
  int i = 0;
  while (i < 5) {
    i++; // update first
    if (i == 3) {
      continue;
    }
    print(i);
  }
}
output
1
2
4
5

8. while (true) With break

Sometimes you don't know the stopping condition until you are inside the loop. Write while (true) — a loop that would run forever — and leave it with break when the moment comes.

dart
void main() {
  int savings = 1000;
  int months = 0;
  while (true) {
    savings += 500;
    months++;
    if (savings >= 3000) {
      break;
    }
  }
  print('Reached $savings after $months months');
}
output
Reached 3000 after 4 months

Every while (true) loop must have a break that is sure to be reached. Without one, the program never ends.


9. break in Nested Loops

When one loop sits inside another, break leaves only the innermost loop it is in. The outer loop carries on.

dart
void main() {
  for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
      if (col == 2) {
        break;
      }
      print('row $row, col $col');
    }
  }
}
output
row 1, col 1
row 2, col 1
row 3, col 1

Each break ends the inner loop for that row. The outer loop still runs all three rows. continue behaves the same way — it skips to the next round of the innermost loop.


10. Labels: Leaving the Outer Loop

To leave both loops at once, give the outer loop a label — a name followed by a colon — and write that name after break.

dart
void main() {
  outer:
  for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
      if (row == 2 && col == 2) {
        break outer;
      }
      print('row $row, col $col');
    }
  }
  print('Done');
}
output
row 1, col 1
row 1, col 2
row 1, col 3
row 2, col 1
Done

break outer ends the loop labelled outer, which also ends the inner loop inside it.


11. continue With a Label

continue outer abandons the rest of the inner loop and starts the next round of the outer loop.

dart
void main() {
  outer:
  for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
      if (col == 2) {
        continue outer;
      }
      print('row $row, col $col');
    }
    print('end of row $row'); // never reached
  }
}
output
row 1, col 1
row 2, col 1
row 3, col 1

Unlike a plain break, continue outer also skips the rest of the outer body, so end of row never prints.


12. A Real-World Example

An ATM gives Ali three tries to enter his PIN. A 0 means he pressed Enter without typing — that try doesn't count. As soon as the PIN is correct, the checking stops.

dart
void main() {
  int correctPin = 4321;
  int attempts = 0;
  bool unlocked = false;

  for (int pin in [1111, 0, 4321, 2222]) {
    if (pin == 0) {
      continue; // empty entry, not counted
    }
    attempts++;
    if (pin == correctPin) {
      unlocked = true;
      break; // correct, stop checking
    }
    if (attempts == 3) {
      break; // out of tries
    }
  }

  print(unlocked ? 'Unlocked after $attempts tries' : 'Card blocked');
}
output
Unlocked after 2 tries

continue filters out the empty entry, break stops on success, and a second break enforces the limit. 2222 is never checked.


Code Examples

Example 1 — Stop at a Number

dart
void main() {
  for (int i = 10; i >= 1; i--) {
    if (i == 7) {
      break;
    }
    print(i);
  }
}
output
10
9
8

Example 2 — Skip a Number

dart
void main() {
  for (int day = 1; day <= 7; day++) {
    if (day == 5) {
      continue;
    }
    print('Day $day');
  }
}
output
Day 1
Day 2
Day 3
Day 4
Day 6
Day 7

Example 3 — Skipping Values in a for-in Loop

dart
void main() {
  for (int n in [4, -2, 7, -5, 3]) {
    if (n < 0) {
      continue;
    }
    print(n);
  }
}
output
4
7
3

Example 4 — First Multiple of 7

dart
void main() {
  int n = 20;
  while (n <= 100) {
    if (n % 7 == 0) {
      print('First multiple of 7: $n');
      break;
    }
    n++;
  }
}
output
First multiple of 7: 21

Example 5 — Doubling Until Over 100

dart
void main() {
  int value = 3;
  while (true) {
    value *= 2;
    if (value > 100) {
      break;
    }
  }
  print(value);
}
output
192

Example 6 — Finding a Pair With a Label

dart
void main() {
  outer:
  for (int a = 1; a <= 5; a++) {
    for (int b = 1; b <= 5; b++) {
      if (a * b == 12) {
        print('Found: $a x $b = 12');
        break outer;
      }
    }
  }
}
output
Found: 3 x 4 = 12

Without the label, break would only end the inner loop, and 4 x 3 would be found as well.

Example 7 — Student Marks

dart
void main() {
  int total = 0;
  int counted = 0;
  for (int mark in [78, -1, 85, 90, -1, 66]) {
    if (mark == -1) {
      continue; // absent
    }
    total += mark;
    counted++;
  }
  print('Counted $counted marks, total $total');
}
output
Counted 4 marks, total 319

-1 means "absent", so continue keeps it out of both the total and the count.

Example 8 — Shopping Total

dart
void main() {
  int budget = 1000;
  int total = 0;
  for (int price in [250, 400, 300, 200]) {
    if (total + price > budget) {
      print('Cannot afford $price, stopping');
      break;
    }
    total += price;
  }
  print('Total: $total');
}
output
Cannot afford 200, stopping
Total: 950

250 + 400 + 300 is 950. Adding 200 would make 1150, so break stops the shopping.

Example 9 — Bank Balance

dart
void main() {
  int balance = 500;
  for (int amount in [120, 200, 300, 50]) {
    if (amount > balance) {
      print('Declined: $amount');
      continue;
    }
    balance -= amount;
    print('Paid $amount, left $balance');
  }
}
output
Paid 120, left 380
Paid 200, left 180
Declined: 300
Paid 50, left 130

continue, not break: one declined payment should not cancel the payments after it.

Example 10 — Temperature Alert

dart
void main() {
  int hour = 0;
  for (double temp in [28.5, 31.0, 999.0, 36.5, 38.0]) {
    hour++;
    if (temp == 999.0) {
      continue; // faulty sensor reading
    }
    if (temp > 35) {
      print('Heat alert at hour $hour: $temp');
      break;
    }
  }
}
output
Heat alert at hour 4: 36.5

999.0 is a sensor error, so continue ignores it. hour++ comes first, so the skipped reading still counts as an hour.


Common Beginner Mistakes

1. Using break outside a loop

dart
void main() {
  int marks = 45;
  if (marks < 50) {
    break;
  }
  print(marks);
}
output
Error: A break statement can't be used outside of a loop or switch statement.
Try removing the break statement.

break leaves a loop, not an if. The same rule applies to continue:

output
Error: A continue statement can't be used outside of a loop or switch statement.

2. Forgetting to update the counter before continue in a while loop

dart
// ✗ never ends: when i is 3, continue skips i++
// int i = 0;
// while (i < 5) {
//   if (i == 3) {
//     continue;
//   }
//   print(i);
//   i++;
// }

This compiles, but prints 0 1 2 and then hangs forever. Move i++ above the continue.

3. Using a label that doesn't exist

dart
void main() {
  for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
      if (col == 2) {
        break outer;
      }
    }
  }
}
output
Error: Can't break to 'outer'.
        break outer;
              ^^^^^

The label must be written in front of a loop that surrounds the break: outer: then for.

4. Writing code after break or continue

Lines after break in the same block can never run. dart analyze flags them as Dead code. Delete them or move them above the break.


Best Practices

  • Use break for searches: stop as soon as the answer is found.
  • Use continue at the top of the loop body to filter out values you want to ignore.
  • In a while loop, update the counter before any continue.
  • Save while (true) for loops whose stopping point is only known inside the loop.
  • Use labels only for nested loops, and keep the nesting shallow.

Mini Challenge

Zayan is reading page numbers 1 to 20. He skips every page that is a multiple of 3, and he stops reading at the first page that is a multiple of 7. Print the pages he reads.

output
1
2
4
5

Try it yourself before opening the solution.

Show solution
dart
void main() {
  for (int page = 1; page <= 20; page++) {
    if (page % 3 == 0) {
      continue;
    }
    if (page % 7 == 0) {
      break;
    }
    print(page);
  }
}
output
1
2
4
5

Pages 3 and 6 are skipped; page 7 reaches the second check, and break ends the loop.


Practice Questions

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

Beginner

  1. Print the numbers 1 to 10, but stop the loop when the number is 6.
  2. Print the numbers 1 to 10, skipping 4 and 8.
  3. Loop over ['Ali', 'Sara', 'Zayan'] and stop when you reach 'Sara', printing only the names before her.

Application

  1. Loop over the prices [120, 0, 75, 0, 300]. Skip the 0 prices and print the total of the rest as Total: ….
  2. Using a while loop, start at n = 50 and find the first number divisible by both 4 and 6. Print Found: ….
  3. Loop over the marks [66, 72, 49, 88]. Print All passed if no mark is below 50, or First fail: … otherwise. Stop at the first fail.
  4. Using while (true), start a bank balance at 200 and add 75 each month. Stop when the balance is at least 500, then print the balance and the number of months.

Challenge

  1. Using a while loop with a counter starting at 0, print the numbers 1 to 10 that are not multiples of 3. Use continue.
  2. Using nested for loops (a and b from 1 to 9), find the first pair where a + b == 10 and a * b == 21. Print it and leave both loops with a label.
  3. Print a table for row 1 to 4. Inside it, loop col from 1 to 4 and print row x col = product. If the product is greater than 6, move on to the next row with continue outer.

Practice Answers

Question 1 — Solution

dart
void main() {
  for (int i = 1; i <= 10; i++) {
    if (i == 6) {
      break;
    }
    print(i);
  }
}
output
1
2
3
4
5

Question 2 — Solution

dart
void main() {
  for (int i = 1; i <= 10; i++) {
    if (i == 4 || i == 8) {
      continue;
    }
    print(i);
  }
}
output
1
2
3
5
6
7
9
10

Question 3 — Solution

dart
void main() {
  for (String name in ['Ali', 'Sara', 'Zayan']) {
    if (name == 'Sara') {
      break;
    }
    print(name);
  }
}
output
Ali

Question 4 — Solution

dart
void main() {
  int total = 0;
  for (int price in [120, 0, 75, 0, 300]) {
    if (price == 0) {
      continue;
    }
    total += price;
  }
  print('Total: $total');
}
output
Total: 495

Question 5 — Solution

dart
void main() {
  int n = 50;
  while (true) {
    if (n % 4 == 0 && n % 6 == 0) {
      break;
    }
    n++;
  }
  print('Found: $n');
}
output
Found: 60

Question 6 — Solution

dart
void main() {
  int? firstFail;
  for (int mark in [66, 72, 49, 88]) {
    if (mark < 50) {
      firstFail = mark;
      break;
    }
  }
  print(firstFail == null ? 'All passed' : 'First fail: $firstFail');
}
output
First fail: 49

firstFail stays null unless a failing mark is found.

Question 7 — Solution

dart
void main() {
  int balance = 200;
  int months = 0;
  while (true) {
    balance += 75;
    months++;
    if (balance >= 500) {
      break;
    }
  }
  print('Balance $balance after $months months');
}
output
Balance 500 after 4 months

Question 8 — Solution

dart
void main() {
  int i = 0;
  while (i < 10) {
    i++;
    if (i % 3 == 0) {
      continue;
    }
    print(i);
  }
}
output
1
2
4
5
7
8
10

Question 9 — Solution

dart
void main() {
  outer:
  for (int a = 1; a <= 9; a++) {
    for (int b = 1; b <= 9; b++) {
      if (a + b == 10 && a * b == 21) {
        print('a = $a, b = $b');
        break outer;
      }
    }
  }
}
output
a = 3, b = 7

Question 10 — Solution

dart
void main() {
  outer:
  for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= 4; col++) {
      int product = row * col;
      if (product > 6) {
        continue outer;
      }
      print('$row x $col = $product');
    }
  }
}
output
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
3 x 1 = 3
3 x 2 = 6
4 x 1 = 4

Quick Revision

  1. What is the difference between break and continue?
  2. Where does the program continue after a break?
  3. In a for loop, does the update part (i++) run after continue?
  4. Why can continue cause an endless while loop?
  5. What must every while (true) loop contain?
  6. In nested loops, which loop does a plain break leave?
  7. How do you write a label, and how do you use it with break?

Key Takeaways

  • break ends the loop immediately; the program carries on after the loop.
  • continue skips the rest of the current round and moves to the next one.
  • Both work in for, for-in, while, and do-while loops.
  • In a for loop, the update still runs after continue; in a while loop, update the counter before continue.
  • while (true) plus a reachable break handles loops whose stopping point is found inside.
  • In nested loops, a plain break or continue affects only the innermost loop.
  • A label (outer:) lets break outer leave, and continue outer skip to the next round of, an outer loop.
  • break and continue outside a loop are compile errors.

What's Next?

Lecture 030 — Introduction to Functions. With break and continue, Category 5 is complete: you can choose which code runs and repeat it exactly as long as you need. But our programs are now long lists of statements inside main(), and the same logic gets copied from place to place. Next we learn functions — how to give a piece of code a name and run it whenever we need it.


Video lecture

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