Break and Continue in C (Simple Explanation with Examples)
When working with loops in C, sometimes we need more control over how the loop behaves.
That’s where break and continue come in.
Let’s understand them in a simple way.
What is break?
The break statement is used to stop the loop immediately.
As soon as break is executed, the loop ends.
Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
if(i == 3) {
break;
}
printf("%d\n", i);
}
return 0;
}๐ Output:
1
2
The loop stops when i becomes 3.
What is continue?
The continue statement is used to skip the current iteration and move to the next one.
Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
if(i == 3) {
continue;
}
printf("%d\n", i);
}
return 0;
}๐ Output:
1
2
4
5
The number 3 is skipped.
Key Difference
- break → stops the loop completely
- continue → skips only one step
When to Use Them?
- Use break when you want to exit early
- Use continue when you want to skip something
Final Thoughts
Both break and continue give you better control over loops.
Understanding them will make your code:
- Smarter
- Cleaner
- More flexible
Thanks for reading!
Comments
Post a Comment