🎓 A1Learner
🔍
0 of 50 lessons completed

C Break and Continue

Break leaves a loop at once, and continue jumps to the next round. Loops ran until their check failed; these two words change that from inside the loop.

Stop the count with break

The loop prints 1, then 2. At i = 3, break ends the loop, so 3 never prints and Stopped follows.

#include <stdio.h>

int main() {
  for (int i = 1; i < 11; i++) {
    if (i == 3) {
      break;
    }
    printf("%d\n", i);
  }
  printf("Stopped.\n");
  return 0;
}

Skip one round with continue

At i = 3, continue skips the print line for that round only. The other numbers print: 1, 2, 4, 5.

#include <stdio.h>

int main() {
  for (int i = 1; i < 6; i++) {
    if (i == 3) {
      continue;
    }
    printf("%d\n", i);
  }
  return 0;
}

Break in a while loop

Count prints 1, 2, then 3. At 4, break ends the loop even though the check count < 100 is still true.

#include <stdio.h>

int main() {
  int count = 1;
  while (count < 100) {
    if (count == 4) {
      break;
    }
    printf("%d\n", count);
    count++;
  }
  printf("Done.\n");
  return 0;
}

Example

#include <stdio.h>

int main() {
  int total = 0;
  for (int i = 1; i < 11; i++) {
    if (i == 5) {
      continue;
    }
    if (i == 8) {
      break;
    }
    total = total + i;
  }
  printf("%d\n", total);
  return 0;
}

Key points

  • break inside a loop ends the loop at once, and the program moves on after the loop.
  • continue inside a loop skips the rest of the round and starts the next round.
  • Use break to stop a search when the answer is found.
  • Use continue to skip a round that is not needed.
  • break and continue work in while loops, do while loops, and for loops.
  • Without break, a loop runs until its check is false.

The loop adds 1, 2, 3, 4, then skips 5, adds 6 and 7, and stops at 8. Those six numbers add to 23.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does break do inside a loop?