← Back to C Course | Chapter 4: Control Flow | Lesson 11 of 11

C break & continue

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

c
#include <stdio.h>
int main() {
	for (int i = 1; i <= 10; i++) {
		if (i == 5) {
			break;
		}
		printf("%d ", i);
	}
	return 0;
}

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

c
#include <stdio.h>
int main() {
	for (int i = 1; i <= 5; i++) {
		if (i == 3) {
			continue;
		}
		printf("%d ", i);
	}
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int i = 1;
	while (i <= 10) {
		if (i == 4) {
			break;
		}
		printf("%d ", i);
		i++;
	}
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int i = 0;
	while (i < 5) {
		i++;
		if (i == 3) {
			continue;
		}
		printf("%d ", i);
	}
	return 0;
}

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

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.