C break and continue Statements – Explained with Examples
In C programming, the break
and continue
statements are used to control the flow of loops and conditional structures. They give you more control over when and how loops execute.
break Statement in C
Purpose:
The break
statement is used to exit a loop or switch statement immediately.
Syntax:
Example: Stop Loop When Number is 5
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
printf("%d ", i);
}
return 0;
}
Output:
1 2 3 4
The loop ends when
i
becomes 5.
continue Statement in C
Purpose:
The continue
statement skips the current iteration and jumps to the next loop cycle.
Syntax:
Example: Skip Number 5 in a Loop
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue;
}
printf("%d ", i);
}
return 0;
}
Output:
1 2 3 4 6 7 8 9 10
The number 5 is skipped.
When to Use
Statement | Use Case |
---|---|
break | To exit a loop or switch-case early |
continue | To skip the current loop iteration and proceed to the next one |
Real-World Example: Validating Input
#include <stdio.h>
int main() {
int number;
while (1) {
printf("Enter a number (0 to exit): ");
scanf("%d", &number);
if (number == 0) {
break; // exit the loop
}
if (number < 0) {
continue; // skip processing for negative numbers
}
printf("You entered: %d\n", number);
}
return 0;
}
Output (Sample):
Enter a number (0 to exit): -5
Enter a number (0 to exit): 10
You entered: 10
Enter a number (0 to exit): 0
Best Practices
Tip | Why It Matters |
---|---|
Use break only when needed | Avoids premature loop exits |
Comment your break /continue | Improves readability and maintenance |
Avoid multiple breaks in large loops | Makes debugging easier |
Common Mistakes
Mistake | Issue |
---|---|
Forgetting to update loop counter | Can lead to infinite loops |
Overusing continue | Makes logic harder to follow |
Misplacing break in nested loops | May exit the wrong loop |