break statement in C ? with example

 

break statement in C

The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following two scenarios:

break statement in C


Syntax:

c
break;

Flowchart of break in c

break statement in C


Example:

c
#include <stdio.h> int main() { int i; for (i = 1; i <= 10; i++) { if (i == 5) { printf("Reached the value 5. Breaking out of the loop.\n"); break; // Exit the loop when i is equal to 5 } printf("Current value of i: %d\n", i); } return 0; }

Output:

Current value of i: 1 Current value of i: 2 Current value of i: 3 Current value of i: 4 Reached the value 5. Breaking out of the loop.

C break statement with the nested loop:


In such case, it breaks only the inner loop, but not outer loop.

Here's an example of how you can use the break statement in nested loops:
c
#include <stdio.h> int main() { for (int i = 1; i <= 3; i++) { printf("Outer loop iteration %d\n", i); for (int j = 1; j <= 3; j++) { printf(" Inner loop iteration %d\n", j); if (i == 2 && j == 2) { printf(" Breaking out of inner loop\n"); break; // This breaks out of the inner loop when i is 2 and j is 2 } } } return 0; }
Output:

Outer loop iteration 1 Inner loop iteration 1 Inner loop iteration 2 Breaking out of inner loop Outer loop iteration 2 Inner loop iteration 1 Outer loop iteration 3 Inner loop iteration 1

break statement with while loop

Consider the following example to use break statement inside while loop:
c
#include <stdio.h> int main() { int i = 1; while (i <= 10) { if (i == 5) { printf("Found the value 5. Breaking out of the loop.\n"); break; // Exit the loop when i is equal to 5 } printf("Current value of i: %d\n", i); i++; } return 0; }
Output:

Current value of i: 1 Current value of i: 2 Current value of i: 3 Current value of i: 4 Found the value 5. Breaking out of the loop.

Post a Comment

0 Comments