break and continue
- Dart course
- Beginner
- Lesson 46/116
- 4 min
Learn to exit a loop with break and skip with continue.
break and continue
Two keywords control the loop flow: break exits the loop completely, continue skips the current iteration and moves to the next. Both are usually used with an if condition.
For example for (var i = 1; i <= 5; i++) { if (i == 3) continue; print(i); } prints 1, 2, 4, 5; when i == 3 continue skips that iteration. break ends the loop entirely.
When to use them?
break is used to end a loop early when a condition is met. For example when searching a list, once the target is found break exits the loop; the remaining elements are not walked in vain.
continue is used to skip elements that meet a certain condition. For example to skip even numbers and process only odd ones you write if (x % 2 == 0) continue;. Practical tip: break means 'stop', continue means 'skip'.
Practice Break at 5
Build a for (var i = 1; i <= 10; i++) loop. In the body first exit at 5 with if (i == 5) { break; }. Then print the number with print(i);. The output must be 4 lines: 1, 2, 3, 4 (one number per line).
Starter code
// Count 1 to 10 with for, break at 5, print eachSample solution
for (var i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
print(i);
}Expected output
1 2 3 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the keyword to its job
| Term | Meaning |
|---|---|
break |
Exits the loop |
continue |
Skips the iteration |
while |
Condition loop |
for |
Counted loop |
2 What is the output of this loop?
for (var i = 1; i <= 3; i++) {
if (i == 2) continue;
print(i);
}- 1 and 3 Correct answer
- 1, 2, 3
- Only 2
- Prints nothing
Explanation: At i=2 continue skips that iteration; 1 and 3 are printed.
3 Write the break keyword
for (var i = 1; i <= 10; i++) {
if (i == 5) {
____;
}
print(i);
}
for (var i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
print(i);
}
Explanation: break exits the loop completely.