Sometimes you need to jump out of a loop early or skip the rest of the current iteration. That's where break and continue come in โ your loop control levers.
break โ Exit the Loop
break immediately terminates the loop. Execution picks up right after the loop body. Great for searching โ once you find what you need, stop.
#include
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
printf("Found 5, stopping\n");
break;
}
printf("Number: %d\n", i);
}
return 0;
}
Try it Yourself โ
continue โ Skip This Iteration
continue skips the rest of the current iteration and jumps straight to the next one. The loop doesn't stop โ it just skips the current round.
#include
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
printf("Odd: %d\n", i);
}
return 0;
}
Try it Yourself โ
break vs continue
break kicks you out of the loop entirely. continue just skips the rest of this round. A common pattern: use continue to filter out unwanted values and break to stop early when a condition is met.
#include
int main() {
for (int i = 1; i <= 10; i++) {
if (i < 3) {
continue;
}
if (i > 8) {
break;
}
printf("Number: %d\n", i);
}
return 0;
}
Try it Yourself โ