C Break and Continue
Sometimes a loop must stop before its condition becomes false, or skip one round. break and continue do exactly that.
break
break leaves the loop at once; the program continues after the loop. It is useful when you have found what you were looking for.
#include <stdio.h>
int main(void) {
int numbers[] = {4, 9, 15, 22, 8};
for (int i = 0; i < 5; i++) {
if (numbers[i] > 10) {
printf("First number above 10: %d (position %d)\n", numbers[i], i);
break;
}
}
return 0;
}First number above 10: 15 (position 2)
You have already seen break in switch, where it ends the switch. Inside a loop it ends the loop.
continue
continue skips the rest of the current round and goes on with the next one.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; // skip multiples of 3
}
printf("%d ", i);
}
printf("\n");
return 0;
}1 2 4 5 7 8 10
In a for loop, continue still runs the step (i++). In a while loop it jumps straight to the condition, so make sure the variable is changed before the continue, or the loop never ends.
An input loop with break
A loop that runs "forever" and stops with break is a common pattern for reading input until a stop value:
#include <stdio.h>
int main(void) {
int total = 0, n;
while (1) {
printf("Number (0 to stop): ");
if (scanf("%d", &n) != 1 || n == 0) {
break;
}
total += n;
}
printf("\nTotal: %d\n", total);
return 0;
}5 12 0
Number (0 to stop): Number (0 to stop): Number (0 to stop): Total: 17
while (1) repeats forever because 1 is always true; the break is the only way out. The program also stops when the input is not a number, because scanf then does not return 1.
Nested loops
break and continue affect only the innermost loop they are in. To leave two loops at once, use a flag variable that the outer loop checks, or put the loops in a function and return.
Practice exercises
- Print the numbers from 1 to 50, but stop at the first one divisible by both 7 and 5.
- Print all numbers from 1 to 20 except the multiples of 4, using
continue. - Read numbers until the user types a negative one, then print how many were read.