Lesson 60 +10 XP

break and continue

break and continue

Two little words with big power inside loops: break stops, continue skips.

break: stop the loop

break jumps out of the loop entirely, immediately:

for (int i = 0; i < 10; i++) {
    if (i == 4) {
        break;
    }
    printf("%d\n", i);
}

Output: 0 1 2 3 (the 4 stops the loop)

continue: skip the rest of this round

continue skips the rest of the body and jumps to the next update:

for (int i = 0; i < 10; i++) {
    if (i == 4) {
        continue;
    }
    printf("%d\n", i);
}

Output: 0 1 2 3 5 6 7 8 9 (4 is skipped)

The difference

  • break ends the entire loop.
  • continue only skips the current iteration.

TL;DR

  • break stops the loop.
  • continue skips to the next iteration.
  • Use break to exit early, continue to skip specific cases.
  • Both work in for, while, and do/while.