Break and continue in C: solved exercise with loops
Break and continue in C: solved exercise
If you searched for a solved break and continue exercise in C, here are the two most common patterns: exiting a loop early with break and skipping an iteration with continue.
Both keywords work inside for, while, and do-while. The difference is straightforward: break exits the entire loop; continue moves to the next iteration, skipping the remainder of the current loop body.
Problem statement
Write a program that iterates from 1 to 20 and:
- Prints only odd numbers (use
continueto skip even numbers). - Stops printing upon reaching the first multiple of 7 greater than 10 (use
break).
C solution
Expected output
Common mistakes
- Using
breakinside aswitchnested in a loop: it only exits theswitch, not the outer loop. - Confusing
continuewithbreak:continuedoes not end the loop, it only skips to the next cycle. - Overusing both statements in ways that make the flow hard to follow; adjusting the loop condition is sometimes cleaner.
- Forgetting that in a
forloop,continuejumps to the increment step, not directly to the condition.
Practical use
break is used to exit search loops as soon as the target is found. continue filters unwanted elements without extra nesting, keeping the code flat and readable.
Recommended next exercise
- For in C: solved exercises
- While and do-while in C: solved exercises
- Switch case in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Does break inside a switch inside a for exit the for?
No. break only exits the innermost enclosing block (switch, for, while, or do-while). To exit the for from inside a switch you need a control variable or carefully placed goto.
Does continue work the same in for, while, and do-while?
Yes, but the jump target differs: in a for loop it jumps to the increment step (i++), while in while and do-while it jumps directly to the condition evaluation.
When is it better to restructure the loop instead of using break or continue?
When these statements make the code harder to read. Sometimes adjusting the loop’s exit condition or extracting the body into a function is cleaner than placing break or continue in the middle of the loop body.