C break & continue
In this page:
The break Statement in Loops
break immediately exits the loop it's inside, skipping any remaining iterations entirely -- execution jumps straight to the first statement after the loop, regardless of what the loop's original condition would have done.
Example: The break Statement in Loops
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
printf("%d ", i);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The continue Statement in Loops
continue skips only the rest of the current iteration's body, then jumps straight to the loop's update step and condition check to begin the next iteration -- unlike break, the loop itself keeps running.
Example: The continue Statement in Loops
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("%d ", i);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using break with while Loops
Inside a while loop, break is commonly used to exit as soon as a specific condition is detected mid-loop, giving you a clean way to stop early instead of needing to redesign the loop's main condition around that case.
Example: Using break with while Loops
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
if (i == 4) {
break;
}
printf("%d ", i);
i++;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using continue with while Loops
When using continue inside a while loop, you must make sure the loop's counter or condition variable is updated before the continue statement runs, or you risk creating an infinite loop that keeps skipping the update step.
Example: Using continue with while Loops
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
i++;
if (i == 3) {
continue;
}
printf("%d ", i);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested Loop Breaks
break only exits the single loop it's physically written inside -- if that loop is nested inside another one, the outer loop is completely unaffected and keeps running its own iterations normally.
Example: Nested Loop Breaks
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break;
}
printf("(%d,%d) ", i, j);
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: