
Think it through together · A little story
A robot checks backpacks one by one. If it finds the target, it ends the search; if it finds an empty space, it skips it and checks the next one.
Lay out the process
- Find an empty spacecontinue skips this round
- Find an ordinary itemCheck it normally
- Find the targetbreak leaves the loop
continue skips the rest of the current iteration; break ends the innermost loop it is in.
One means “skip this turn”; the other means “the search ends here.” You can lay out cards on a table to act this out.
01Why change a loop’s flow early?
Sometimes a loop does not need to keep running as planned until the very end.
For example, it can end early after finding a target, or skip the current iteration when data does not need to be handled.
02break: end the loop immediately
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
std::cout << i << ' ';
}
Output:
1 2 3 4
When i == 5, break ends this loop immediately.
03continue: skip this iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
std::cout << i << ' ';
}
Output:
1 2 4 5
continue does not end the whole loop; it skips only the remaining code in the current iteration.
04Where does a for loop go after continue?
In a for loop, after continue runs, execution first goes to the loop’s update expression, then checks the condition again.
This is an easy detail for beginners to miss.
05Where does a while loop go after continue?
In a while loop, continue goes straight back to the condition check.
06How many levels does break exit in nested loops?
for (...) {
for (...) {
if (found) {
break;
}
}
}
This break ends only the innermost loop it is in. It does not automatically end the outer loop too.
07When should you avoid overusing them?
Using break and continue in moderation can make code clearer, but jumping around everywhere makes control flow hard to follow.
After writing them, ask: “Can someone else easily see where execution goes next?”
What you have learned
breakimmediately ends the innermost current loop.continueskips only the rest of the current iteration.- In a for loop, the update expression runs after continue.
- In a while loop, continue goes back to the condition check.
- A break in a nested loop does not automatically exit every level.
Next: How do you follow a program’s execution step by step?
Your turn to try
If you want to skip a bad apple but still check the apples after it, which statement should you use?
Have you thought it through? Open for an explanation
Use continue. break would end this loop, so the later apples would not be checked.