
Break and Continue Statements in C
The break
and continue
statements are used to control loop execution in C.
"The `break` statement terminates the loop, while `continue` skips the current iteration and proceeds with the next."
What Are `break` and `continue` Statements?
These statements alter the normal flow of loop execution:
break
- Immediately exits a loop or switch statement.continue
- Skips the current iteration and jumps to the next loop cycle.
Comparison of `break` and `continue`
Statement | Description | Example Usage |
---|---|---|
break |
Exits the loop immediately. | Stop a loop when a condition is met. |
continue |
Skips the current iteration and moves to the next. | Skip even numbers in a loop. |
Examples of `break` Statement
1. Using `break` in a `for` Loop
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i == 5
}
printf("%d ", i);
}
return 0;
}
2. Using `break` in a `while` Loop
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
if (i == 6) {
break; // Exit the loop when i == 6
}
printf("%d ", i);
i++;
}
return 0;
}
3. Using `break` in a `switch` Statement
#include <stdio.h>
int main() {
int choice = 2;
switch (choice) {
case 1:
printf("Choice is 1\n");
break;
case 2:
printf("Choice is 2\n");
break;
case 3:
printf("Choice is 3\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}
Examples of `continue` Statement
1. Using `continue` in a `for` Loop
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}
2. Using `continue` in a `while` Loop
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}
Important Notes on `break` and `continue`
- `break`: Completely exits the loop or `switch` block.
- `continue`: Skips the rest of the current iteration and moves to the next cycle.
- Use in Nested Loops: `break` exits the **inner loop** only, while `continue` affects only the **current loop iteration**.
Best Practices for Using `break` and `continue`
- Use `break` to **exit loops early** when a condition is met.
- Use `continue` to **skip unwanted iterations** without stopping the loop.
- Be cautious while using `continue` inside **nested loops** to avoid unexpected behavior.
Example: Nested Loops with `break` and `continue`
#include <stdio.h>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue; // Skip printing when j == 2
}
printf("(%d, %d) ", i, j);
}
printf("\n");
}
return 0;
}
Conclusion
The `break` and `continue` statements provide greater control over loop execution in C. Understanding their behavior helps write more efficient programs! 🚀