The break statement is used to prevent the current execution of loop in between even though the specified condition is true in loop or the next switch case. In case of nested loop, it breaks the continuity of the loop in which break statement specified, i.e, if break statement specified in the inner loop, external loops will not get affected because of Break statement.
Loop with break statement
The break statement is used to prevent further execution of loop if control encounter break statement. Similarly, break statement used with other loop as well.
1 loop/switch {
2
3 break;
4 }
break with for
1 #include <stdio.h>
2
3 int main() {
4 int i = 0;
5 for(;;) {
6 if(i == 5)
7 break;
8 printf("%d ", i);
9 i++;
10 }
11 return 0;
12 }
In the above example, a variable is declare with initial value 0 and a for loop specified without expression that validates termination condition once a value of variable i become 5 using break statement. Otherwise, variable value i will be printed and increase by 1.
break with while loop
While loop with break statement
1 #include <stdio.h>
2
3 int main() {
4 int i = 0;
5 while(i < 5) {
6 printf("%d ", i);
7 i++;
8
9 if(i == 2)
10 break;
11 }
12 return 0;
13 }
In the above example, a variable i is declared with initial value 0 and a while loop continue until variable i value less than 5. A current value will be printed using printf() and increase by 1. If value of variable i is 2, it executes break statement and terminate from loop.
Switch with break statement
The switch statement expects an expression which possible value need to match with defined cases. Once the case gets executes it need to be terminated from switch statement otherwise next all cases will be executed one by one. If you have more than one statement other than break statement use curly braces.
Switch with break statement
1 #include <stdio.h>
2
3 int main() {
4 int val;
5 printf("Enter value from 1 to 2 : ");
6 scanf("%d", &val);
7
8 switch(val) {
9 case 1:
10 printf("One");
11 break;
12 case 2:
13 printf("Two");
14 break;
15 default:
16 printf("Invalid input !!");
17 break;
18 }
19 printf("\nProgram about to terminate !!");
20 return 0;
21 }
In the above example, a value accepted from user and assigned to variable val. It specified in the switch statement and compare with case statements. If case matches with value, it prints string representation of value and break from the case block. If value does not match, it executes default case.
1 Enter value from 1 to 2 : 2
2 Two
3 Program about to terminate !!
4
5 Enter value from 1 to 2 : 5
6 Invalid input !!
7 Program about to terminate !!
Related options for your search