Loop Control: break & continue
Learn how to terminate loops early or skip specific iterations using jump statements.
1. The break Statement
The break statement immediately halts execution of the innermost active loop and transfers control outside:
// Stop looping as soon as target is found
let target: int = 7;
for i in 1 to 20 {
if i == target {
print("Found target:", i);
break;
}
print("Searching at:", i);
}
2. The continue Statement
The continue statement skips the rest of the current iteration and jumps directly to the next cycle:
// Print only odd numbers
for n in 1 to 10 {
if n % 2 == 0 {
continue; // Skip even numbers
}
print("Odd number:", n);
}