Examples of break in C
Example 1: C Program to use break Statement with Simple Loops
Break statements in C can be used with simple loops i.e, for loops, while loops, and do-while loops.
C
// C Program to demonstrate break statement with for loop #include <stdio.h> int main() { // using break inside for loop to terminate after 2 // iteration printf ( "break in for loop\n" ); for ( int i = 1; i < 5; i++) { if (i == 3) { break ; } else { printf ( "%d " , i); } } // using break inside while loop to terminate after 2 // iteration printf ( "\nbreak in while loop\n" ); int i = 1; while (i < 20) { if (i == 3) break ; else printf ( "%d " , i); i++; } return 0; } |
break in for loop 1 2 break in while loop 1 2
Example 2: C Program to use break Statement with Nested Loops
Break statements can also be used when working with nested loops. The control will come out of only that loop in which the break statement is used.
C
// C program to illustrate // using break statement // in Nested loops #include <stdio.h> int main() { // nested for loops with break statement // at inner loop for ( int i = 1; i <= 6; ++i) { for ( int j = 1; j <= i; ++j) { if (i <= 4) { printf ( "%d " , j); } else { // if i > 4 then this innermost loop will // break break ; } } printf ( "\n" ); } return 0; } |
1 1 2 1 2 3 1 2 3 4
Note: Break statement only breaks out of one loop at a time. So if in nested loop, we have used break in inner loop, the control will come to outer loop instead of breaking out of all the loops at once. We will have to use multiple break statements if we want to break out of all the loops.
Example 3: C Program to use break Statement with Infinite Loops
An Infinite loop can be terminated with a break statement as a part of the condition.
C
// C Program to demonstrate infinite loop without using // break statement #include <stdio.h> int main() { int i = 0; // while loop which will always be true while (1) { printf ( "%d " , i); i++; if (i == 5) { break ; } } return 0; } |
0 1 2 3 4
In the above program, the loop condition is always true, which will cause the loop to execute indefinitely. This is corrected by using the break statement. Iteration of the loop is restricted to 8 iterations using break.
Break Statement in C
The break statement is one of the four jump statements in the C language. The purpose of the break statement in C is for unconditional exit from the loop