๐ C Break and Continue Statements – Loop Control
In C, the break and continue statements are used to control how loops behave.
breakโ Exits the loop completely.continueโ Skips the current iteration and moves to the next one.
๐น The break Statement
The break statement is often used when you want to exit a loop early based on a condition.
๐ Example 1: Break in a For Loop
This loop stops when i equals 4.
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
printf("Number: %d\n", i);
}
return 0;
}
๐ Example 2: Break in a While Loop
This while loop ends when count reaches 5.
#include <stdio.h>
int main() {
int count = 1;
while (count <= 10) {
if (count == 5) {
break;
}
printf("Count: %d\n", count);
count++;
}
return 0;
}
๐น The continue Statement
Use continue to skip specific iterations in a loop without exiting it.
๐ Example 3: Continue in a For Loop
This loop skips printing when i is 5.
#include <stdio.h>
int main() {
for (int i = 1; i <= 7; i++) {
if (i == 5) {
continue;
}
printf("i = %d\n", i);
}
return 0;
}
๐ Example 4: Continue in a While Loop
This skips printing even numbers.
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue;
}
printf("%d is odd\n", i);
}
return 0;
}
๐ฏ Summary
breakends the loop immediately.continueskips the current loop iteration.
๐ก Challenge Time!
Try using break and continue in nested loops. Can you print a triangle pattern but skip the middle row?