Break Statement
break immediately exits the nearest enclosing loop or switch statement:
for (int i = 1; i <= 10; i++) {
if (i == 5) break; // stop at 5
print(i);
}
// Prints: 1 2 3 4
Continue Statement
continue skips the rest of the current iteration and jumps to the next one:
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
print(i);
}
// Prints: 1 3 5 7 9
Labeled Break/Continue
Use labels to break out of or continue an outer loop from an inner loop:
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) continue outer; // skip to next i
print('i=$i, j=$j');
}
}
// i=0,j=0 i=1,j=0 i=2,j=0
Full Example
void main() {
// Find first number divisible by both 3 and 7
for (int n = 1; n <= 200; n++) {
if (n % 3 == 0 && n % 7 == 0) {
print('First divisible by 3 and 7: $n');
break;
}
}
// Print only odd numbers 1-20
print('Odd numbers:');
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) continue;
print(i);
}
}
Output:First divisible by 3 and 7: 21
Odd numbers: 1 3 5 7 9 11 13 15 17 19
🧠 Quiz
1. What does break do in a loop?
- A) Skips current iteration
- B) Exits the loop entirely ✅
- C) Restarts the loop
- D) Pauses execution
2. What does continue do?
- A) Exits the loop
- B) Skips to the next iteration ✅
- C) Restarts from beginning
- D) Breaks out of a switch
Summary
break exits the loop immediately. continue skips the current iteration and moves to the next. Labels let you target outer loops. Use these to write efficient loop logic that handles special cases.