On this page24 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. Why Stop a Loop Early?
- 2. break Leaves the Loop
- 3. After break, the Program Continues Below the Loop
- 4. continue Skips One Round
- 5. break vs continue
- 6. break and continue in a for-in Loop
- 7. break and continue in a while Loop
- 8. while (true) With break
- 9. break in Nested Loops
- 10. Labels: Leaving the Outer Loop
- 11. continue With a Label
- 12. 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 29 — break & continue
| Category | 5 — Control Flow |
| Lecture | 029 of 140 |
| Estimated video length | 8 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
A loop so far runs every round until its condition turns false.
breaklets you leave a loop early, andcontinuelets 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
++,+=,%,==,&& ifandif-else(Lectures 022–023)forloops (Lecture 026)for-inloops over a list written in square brackets, such as[80, 45, 90](Lecture 027)whileanddo-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
breakandcontinuedo - Use
breakto leave a loop as soon as the answer is found - Use
continueto skip the rest of one round - Use both in
for,for-in, andwhileloops - Write a
while (true)loop that ends withbreak - Predict how
breakbehaves inside nested loops - Use a label such as
outer:to leave or skip an outer loop - Recognize the error messages Dart gives for misplaced
breakandcontinue
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.
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
print(i);
}
}1
2
3The 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.
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 3) {
break;
}
print('Round $i');
}
print('Loop finished');
}Round 1
Round 2
Loop finished4. continue Skips One Round
continue stops the current round and jumps straight to the next one. The loop itself
keeps going.
void main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
print(i);
}
}1
2
4
5When 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
break | continue | |
|---|---|---|
| Stops the current round? | yes | yes |
| Runs more rounds? | no — the loop is over | yes — 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:
void main() {
for (int mark in [80, 92, 45, 70, 38]) {
if (mark < 50) {
print('First failing mark: $mark');
break;
}
}
}First failing mark: 4538 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:
void main() {
int balance = 100;
while (balance > 0) {
balance -= 30;
if (balance < 50) {
break;
}
print('Balance: $balance');
}
print('Stopped at $balance');
}Balance: 70
Stopped at 40continue 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:
void main() {
int i = 0;
while (i < 5) {
i++; // update first
if (i == 3) {
continue;
}
print(i);
}
}1
2
4
58. 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.
void main() {
int savings = 1000;
int months = 0;
while (true) {
savings += 500;
months++;
if (savings >= 3000) {
break;
}
}
print('Reached $savings after $months months');
}Reached 3000 after 4 monthsEvery 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.
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');
}
}
}row 1, col 1
row 2, col 1
row 3, col 1Each 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.
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');
}row 1, col 1
row 1, col 2
row 1, col 3
row 2, col 1
Donebreak 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.
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
}
}row 1, col 1
row 2, col 1
row 3, col 1Unlike 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.
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');
}Unlocked after 2 triescontinue 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
void main() {
for (int i = 10; i >= 1; i--) {
if (i == 7) {
break;
}
print(i);
}
}10
9
8Example 2 — Skip a Number
void main() {
for (int day = 1; day <= 7; day++) {
if (day == 5) {
continue;
}
print('Day $day');
}
}Day 1
Day 2
Day 3
Day 4
Day 6
Day 7Example 3 — Skipping Values in a for-in Loop
void main() {
for (int n in [4, -2, 7, -5, 3]) {
if (n < 0) {
continue;
}
print(n);
}
}4
7
3Example 4 — First Multiple of 7
void main() {
int n = 20;
while (n <= 100) {
if (n % 7 == 0) {
print('First multiple of 7: $n');
break;
}
n++;
}
}First multiple of 7: 21Example 5 — Doubling Until Over 100
void main() {
int value = 3;
while (true) {
value *= 2;
if (value > 100) {
break;
}
}
print(value);
}192Example 6 — Finding a Pair With a Label
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;
}
}
}
}Found: 3 x 4 = 12Without the label, break would only end the inner loop, and 4 x 3 would be found as well.
Example 7 — Student Marks
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');
}Counted 4 marks, total 319-1 means "absent", so continue keeps it out of both the total and the count.
Example 8 — Shopping Total
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');
}Cannot afford 200, stopping
Total: 950250 + 400 + 300 is 950. Adding 200 would make 1150, so break stops the shopping.
Example 9 — Bank Balance
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');
}
}Paid 120, left 380
Paid 200, left 180
Declined: 300
Paid 50, left 130continue, not break: one declined payment should not cancel the payments after it.
Example 10 — Temperature Alert
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;
}
}
}Heat alert at hour 4: 36.5999.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
void main() {
int marks = 45;
if (marks < 50) {
break;
}
print(marks);
}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:
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
// ✗ 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
void main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
if (col == 2) {
break outer;
}
}
}
}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
breakfor searches: stop as soon as the answer is found. - Use
continueat the top of the loop body to filter out values you want to ignore. - In a
whileloop, update the counter before anycontinue. - 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.
1
2
4
5Try it yourself before opening the solution.
Show solution
void main() {
for (int page = 1; page <= 20; page++) {
if (page % 3 == 0) {
continue;
}
if (page % 7 == 0) {
break;
}
print(page);
}
}1
2
4
5Pages 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
- Print the numbers
1to10, but stop the loop when the number is6. - Print the numbers
1to10, skipping4and8. - Loop over
['Ali', 'Sara', 'Zayan']and stop when you reach'Sara', printing only the names before her.
Application
- Loop over the prices
[120, 0, 75, 0, 300]. Skip the0prices and print the total of the rest asTotal: …. - Using a
whileloop, start atn = 50and find the first number divisible by both4and6. PrintFound: …. - Loop over the marks
[66, 72, 49, 88]. PrintAll passedif no mark is below50, orFirst fail: …otherwise. Stop at the first fail. - Using
while (true), start a bank balance at200and add75each month. Stop when the balance is at least500, then print the balance and the number of months.
Challenge
- Using a
whileloop with a counter starting at0, print the numbers1to10that are not multiples of3. Usecontinue. - Using nested
forloops (aandbfrom1to9), find the first pair wherea + b == 10anda * b == 21. Print it and leave both loops with a label. - Print a table for
row1to4. Inside it, loopcolfrom1to4and printrow x col = product. If the product is greater than6, move on to the next row withcontinue outer.
Practice Answers
Question 1 — Solution
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
print(i);
}
}1
2
3
4
5Question 2 — Solution
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 4 || i == 8) {
continue;
}
print(i);
}
}1
2
3
5
6
7
9
10Question 3 — Solution
void main() {
for (String name in ['Ali', 'Sara', 'Zayan']) {
if (name == 'Sara') {
break;
}
print(name);
}
}AliQuestion 4 — Solution
void main() {
int total = 0;
for (int price in [120, 0, 75, 0, 300]) {
if (price == 0) {
continue;
}
total += price;
}
print('Total: $total');
}Total: 495Question 5 — Solution
void main() {
int n = 50;
while (true) {
if (n % 4 == 0 && n % 6 == 0) {
break;
}
n++;
}
print('Found: $n');
}Found: 60Question 6 — Solution
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');
}First fail: 49firstFail stays null unless a failing mark is found.
Question 7 — Solution
void main() {
int balance = 200;
int months = 0;
while (true) {
balance += 75;
months++;
if (balance >= 500) {
break;
}
}
print('Balance $balance after $months months');
}Balance 500 after 4 monthsQuestion 8 — Solution
void main() {
int i = 0;
while (i < 10) {
i++;
if (i % 3 == 0) {
continue;
}
print(i);
}
}1
2
4
5
7
8
10Question 9 — Solution
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;
}
}
}
}a = 3, b = 7Question 10 — Solution
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');
}
}
}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 = 4Quick Revision
- What is the difference between
breakandcontinue? - Where does the program continue after a
break? - In a
forloop, does the update part (i++) run aftercontinue? - Why can
continuecause an endlesswhileloop? - What must every
while (true)loop contain? - In nested loops, which loop does a plain
breakleave? - How do you write a label, and how do you use it with
break?
Key Takeaways
breakends the loop immediately; the program carries on after the loop.continueskips the rest of the current round and moves to the next one.- Both work in
for,for-in,while, anddo-whileloops. - In a
forloop, the update still runs aftercontinue; in awhileloop, update the counter beforecontinue. while (true)plus a reachablebreakhandles loops whose stopping point is found inside.- In nested loops, a plain
breakorcontinueaffects only the innermost loop. - A label (
outer:) letsbreak outerleave, andcontinue outerskip to the next round of, an outer loop. breakandcontinueoutside 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.