break and continue are control flow statements used in loops in C programming. Break terminates the loop prematurely when a certain condition is met, while continue skips the current iteration and moves to the next iteration of the loop. They are handy tools for fine-tuning the flow of execution within loops, enhancing code readability and efficiency.
break statement terminates any type of 'loop' or 'switch case'. The break statement terminates the loop body immediately and passes control to the next statement after the loop.
Syntaxbreak;Example
#include<stdio.h> int main() { int n=0; while(n<=50) { printf("value of variable n=%d", num); if (n==5) { break; } n++; printf("Out of while-loop"); } }Output
value of variable n=0 value of variable n=1 value of variable n=2 value of variable n=3 value of variable n=4 value of variable n=5 Out of while-loop
In C Programs, if we want to take control to the beginning of the loop, by passing the statements inside the loop, which have not yet been executed, in this case we use continue. When continue is encountered inside any loop, control automatically passes to the beginning of loop. A continue is usually associated with if Statement.
Syntaxcontinue;Example
#include<stdio.h> int main() { int i; for (i = 0; i <= 8; i++) { if (i == 4) { continue; } printf("%d ", i); } return 0; }Output
0 1 2 3 5 6 7 8
Value 4 is missing in the output,because the value of variable i is 4, the program encountered a continue statement, which makes the control to jump at the beginning of the for loop for next iteration, skipping the statements for current iteration.
Difference Between break and continueS.No | break | continue |
---|---|---|
1. | when break is executed, statement following the break are skipped.and causes the loop to be terminated. | When continue gets executed statement following the continue are skipped and causes the loop to continued with the next iteration. |
2. | Syntaxbreak; | Syntaxcontinue; |
3. | It can be used in switch statement to transfer the control outside the switch. | It cannot be used inside the switch. |
4. | for(i=1 ;i<=10; i++) { Example if(i==3) break; printf("%d\t",i); } | for(i=1 ;i<=10; i++) { Example if(i==3) continue; printf("%d\t",i); } |