3.4 break and continue
break and continue both change the normal flow of a loop, but they mean different things.
break: end the current loop immediately.continue: skip the rest of the current iteration and start the next one.
break
Use break when the loop has already met its goal, or when continuing makes no sense.
The program below checks whether an integer is a prime number. As soon as it finds a number that divides n, it can confirm that n is not prime, with no need to keep checking.
#include <stdio.h>
#include <math.h>
int main(void) {
int n;
scanf("%d", &n);
int is_prime = n > 1;
for (int i = 2; i <= (int)sqrt(n); i++) {
if (n % i == 0) {
is_prime = 0;
break;
}
}
if (is_prime) {
printf("%d is prime\n", n);
} else {
printf("%d is not prime\n", n);
}
return 0;
}One possible run:
17
17 is primeThere is no need to check up to n - 1. If a number has a factor greater than its square root, it must also have a paired factor smaller than the square root, so checking up to sqrt(n) is enough.
continue
continue does not end the whole loop. It skips the remaining code in the current iteration and goes straight to the next one.
The program below reads 10 integers and sums the squares of the non-negative ones only. When it meets a negative number, it skips that iteration.
int n = 10;
int sum_square = 0;
for (int i = 0; i < n; i++) {
int num;
scanf("%d", &num);
if (num < 0) {
continue;
}
sum_square += num * num;
}
printf("Sum of squares of non-negatives: %d\n", sum_square);When num < 0, continue skips sum_square += num * num, so negative numbers do not take part in the calculation.
0 is not negative; its square is 0, and adding it does not change the total.How to choose
If you want "the whole loop stops here," use break. If you only want "skip the rest of this round, but keep looping," use continue.
for (int x = 1; x <= 5; x++) {
if (x == 3) {
continue;
}
printf("%d\n", x);
}Output:
1
2
4
53 is skipped, but the loop does not end.
Comparison experiment
After reading what break and continue mean, use the component below to compare them step by step. When the loop reaches x == 3, continue only skips the current iteration, while break ends the whole loop early.