Step 6 of 7
break and continue
Inside any loop (loop, while or for):
breakends the loop right away.continueskips the rest of the current iteration and moves on to the next one.
fn main() {
for n in 1..=10 {
if n % 3 == 0 {
continue;
}
if n > 7 {
break;
}
print!("{n} ");
}
println!();
}
1 2 4 5 7
Trace it: 3 and 6 are skipped by continue. At 8, break ends the loop, so 8, 9 and 10 never print.
continue is handy for skipping values you don't care about without wrapping the rest of the body in an if. Many teams prefer this "skip early" shape for the same reason they like guard clauses.
Stopping a search
break is the natural way to stop a search as soon as you've found the answer, instead of checking every remaining value:
fn main() {
let target = 91;
let mut smallest_divisor = target;
for d in 2..target {
if target % d == 0 {
smallest_divisor = d;
break;
}
}
println!("smallest divisor of {target}: {smallest_divisor}");
}
smallest divisor of 91: 7
Inside a function, return also ends the loop (and the function) immediately. A search often reads best as its own function: return the answer as soon as you find it, and put the "not found" result after the loop.
Common mistakes
continuebefore the update in awhileloop:
let mut i = 0;
while i < 10 {
if i % 2 == 0 {
continue; // i never changes again: an infinite loop
}
i += 1;
}
In a for loop this can't happen, because the range moves on by itself.
- Expecting
breakto leave every loop: it only leaves the innermost one. The next step shows how to break out of an outer loop.
Your task
Write fn is_prime(n: u32) -> bool. A prime number has exactly two divisors, 1 and itself, so 0 and 1 are not prime. Check the possible divisors from 2 upward, and stop as soon as you find one.
Challenge 2
Print the numbers from 1 to 20 on one line, but skip multiples of 4 with continue, and stop the loop completely with break as soon as the number is greater than 15:
1 2 3 5 6 7 9 10 11 13 14 15
Challenge 3
The starter code has a working is_prime. Write fn count_primes(limit: u32) -> u32 that counts the primes from 2 up to and including limit, by calling is_prime in a for loop. Use continue to skip the numbers that aren't prime.
Previous: for loops and ranges Next: Nested loops and labels