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:

  1. Prints only odd numbers (use continue to skip even numbers).
  2. Stops printing upon reaching the first multiple of 7 greater than 10 (use break).

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 20; i++) {
        if (i % 2 == 0) continue;        /* skip even numbers */
        if (i % 7 == 0 && i > 10) break; /* stop at first multiple of 7 > 10 */
        printf("%d\n", i);
    }
    return 0;
}

Expected output

1
2
3
4
5
6
7
1
3
5
7
9
11
13

Common mistakes

  • Using break inside a switch nested in a loop: it only exits the switch, not the outer loop.
  • Confusing continue with break: continue does 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 for loop, continue jumps 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.

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.