break and continue
break stops a loop completely, while continue just skips the rest of the current lap and moves to the next one.
Using break to Exit Early
break immediately stops the loop entirely, skipping any remaining iterations.
Example: Using break to Exit Early
for number in 1...10 {
if number == 4 {
break
}
print("Number: \(number)")
}
Login to try C/C++/Java/PHP code in the editor
Using continue to Skip an Iteration
continue skips the rest of the current iteration's code and jumps straight to the next one, without stopping the loop entirely.
Example: Using continue to Skip an Iteration
for number in 1...6 {
if number % 2 == 0 {
continue
}
print("Odd number: \(number)")
}
Login to try C/C++/Java/PHP code in the editor
Labeled Loops
A label placed before a loop lets break or continue target that specific loop even from inside a nested loop.
Example: Labeled Loops
outer: for i in 1...3 {
for j in 1...3 {
if j == 2 {
continue outer
}
print("i=\(i), j=\(j)")
}
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using
breakwhen the intent was only to skip the current iteration; that requirescontinue, notbreak. - Forgetting that
breakinside aswitchexits the switch itself, not an enclosing loop -- use a labeled break for that case. - Placing code after a
continuein the same iteration expecting it to still run; nothing aftercontinueexecutes for that pass.
Chapter Summary
breakimmediately exits the nearest enclosing loop (or switch).continueskips the rest of the current iteration and moves to the next one.- Labeled loops (
outerLoop: for ...) letbreakorcontinuetarget a specific outer loop. - Both are commonly combined with an
ifcondition to control loop flow.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: