Break vs Continue in C
0 1097
Break statement in C
In C, the break statement stops the loop before it finishes. When the break statement is encountered within a loop, the loop is immediately exited, and the program control resumes at the next statement following the loop. Syntax of Break Statement in C:break;Purpose: The break statement is used to terminate the execution of a loop immediately when a certain condition is met. Effect: When encountered within a loop, the break exits the loop entirely, and the program control resumes at the next statement following the loop. Use Cases: Exiting a loop prematurely when a specific condition is satisfied. Terminating a loop if an error condition occurs. Example:
// program for break in C #include<stdio.h>Output:int main() { int A; for(A = 1; A <= 10; A++) { if(A == 5) { printf("Encountered 5. Exiting loop.\n"); break; } printf("%d\n", i); } return 0; }
1 2 3 4 Encountered 5. Exiting loop.
Continue Statement in C
The continue statement in C is used to skip the rest of the statements within a loop for the current iteration and proceed with the next iteration of the loop. Syntax of continue statement in Ccontinue;Purpose: The continue statement is used to skip the rest of the statements within a loop for the current iteration and proceed with the next iteration of the loop. Effect: When encountered within a loop, continue to skip the remaining statements in the loop's body for the current iteration and proceed with the next iteration. Use Cases: Skipping certain iterations in a loop based on specific conditions. Continuing with the next iteration if certain conditions are met without executing the remaining statements in the loop. Example:
// program for continue in C #include<stdio.h>Output:int main() { int i; for(i = 1; i <= 5; i++) { if(i == 3) { printf("Skipping iteration %d.\n", i); continue; } printf("%d\n", i); } return 0; }
1 2 Skipping iteration 3. 4 5
Difference between break and continue statement
| Feature | break | continue |
| Purpose | Terminates the loop immediately and exits from it | Skips the rest of the loop for the current iteration |
| Effect | Exits the innermost loop if used inside nested loops | Skips the remaining statements in the current iteration and continues with the next one |
| Use Cases | Exiting loop when a certain condition is met | Skipping certain iterations in the loop |
| Statement Format | `break;` | `continue;` |
Share:




Comments
Waiting for your comments