1. Introduction
In C programming, break and continue are two control statements used within loops. They alter the normal flow of a loop in different ways. break is used to exit the loop immediately, while continue skips the rest of the code in the current iteration and proceeds to the next iteration of the loop.
2. Key Points
1. break terminates the loop entirely and resumes execution at the first statement following the loop.
2. continue skips the remaining statements in the current loop iteration and jumps to the next iteration.
3. break is often used for exiting a loop when a specific condition is met.
4. continue is used when you want to skip the current iteration based on certain conditions but continue with the loop.
3. Differences
break | continue |
---|---|
Exits the loop immediately. | Skips to the next iteration of the loop. |
Used to exit the loop or switch statement. | Only applicable in loop statements. |
Loop conditions are not checked again. | Loop continues, and conditions are checked for subsequent iterations. |
4. Example
#include <stdio.h>
int main() {
// Example using break
for (int i = 0; i < 10; i++) {
if (i == 5) break;
printf("%d ", i);
}
printf("\nBreak used to exit loop.\n");
// Example using continue
for (int i = 0; i < 10; i++) {
if (i == 5) continue;
printf("%d ", i);
}
printf("\nContinue used to skip iteration.\n");
return 0;
}
Output:
0 1 2 3 4 Break used to exit loop. 0 1 2 3 4 6 7 8 9 Continue used to skip iteration.
Explanation:
1. In the break example, the loop exits when i equals 5. Numbers after 5 are not printed.
2. In the continue example, the loop skips the iteration where i equals 5 and continues with the rest of the iterations.
5. When to use?
- Use break when you need to exit a loop prematurely, such as when a termination condition is met, or in case of an error that requires exiting the loop.
- Use continue when you need to skip the current iteration and move to the next iteration, often used for filtering or avoiding specific conditions within the loop.
Difference between malloc() and calloc()?
Difference between Local Variable and Global Variable in C
Difference between Global and Static Variables in C
Difference Between Call by Value and Call by Reference in C
Difference Between getch() and getche() in C
Difference between printf() and sprintf() in C
Difference between Arrays and Pointers in C
Difference between Structure and Union in C
Difference Between Stack and Heap Memory Allocation in C
Difference Between Macro and Function in C
Difference between = and == in C
Difference Between for loop and while loop in C
Difference Between Linked List and Array in C
Difference between fgets() and gets() in C
Difference between ++i and i++ in C
Difference between struct and typedef struct in C
Difference between int main() and void main() in C
Difference between Character Array and String in C
Comments
Post a Comment
Leave Comment