break in C
The break statement exits or terminates the loop or switch statement based on a certain condition, without executing the remaining code.
Syntax of break in C
break;
Flowchart of break Statement
Uses of break in C
The break statement is used in C for the following purposes:
- To come out of the loop.
- To come out from the nested loops.
- To come out of the switch case.
Note: If the break statement is used inside an inner loop in a nested loop, it will break the inner loop without affecting the execution of the outer loop.
Example of break Statement
The statements inside the loop are executed sequentially. When the break statement is encountered within the loop and the condition for the break statement becomes true, the program flow breaks out of the loop, regardless of any remaining iterations.
C
// C program to illustrate the break in c loop #include <stdio.h> int main() { int i; // for loop for (i = 1; i <= 10; i++) { // when i = 6, the loop should end if (i == 6) { break ; } printf ( "%d " , i); } printf ( "Loop exited.\n" ); return 0; } |
1 2 3 4 5 Loop exited.
Explanation:
- Loop Execution Starts and goes normally till i = 5.
- When i = 6, the condition for the break statement becomes true and the program control immediately exits the loop.
- The control continues with the remaining statements outside the loop.
Note: The break statement only break a single loop per usage. If we want to exit multiple loops in nested loops, we have to use multiple break statements for each of the loop.
The break statement is also used inside the switch statement to terminate the switch statement after the matching case is executed.
Jump Statements in C
In C, jump statements are used to jump from one part of the code to another altering the normal flow of the program. They are used to transfer the program control to somewhere else in the program.
In this article, we will discuss the jump statements in C and how to use them.