Break statement in C
In this tutorial, you’ll learn about break statement in C and how to use it with-in your C program.
Break statement
The break is a keyword in C programming which is used to bring the control of the program outside of the loop. The break statement is used inside loops or switch statement.
The break statement terminates the loop in a sequence i.e., in the case of nested loops, it terminates the inner loop first and then the outer loops. Break statement is usually used with if statement whenever it comes inside a loop. It terminates the loop or switch statement and executes the statement following the loop or switch.
Syntax
Statements (loop or switch)
break;
Example– Use of break in a while loop
[maxbutton id=”1″ url=”https://coderseditor.com/?id=172″ ]
#include <stdio.h> int main() { int num =0; while(num<=100) { printf("value of variable num is: %d\n", num); if (num==2) { break; } num++; } return 0; }
Output
value of variable num is: 0
value of variable num is: 1
value of variable num is: 2
Example – Use of break in a for loop
[maxbutton id=”1″ url=”https://coderseditor.com/?id=173″ ]
#include <stdio.h> int main() { int var; for (var =100; var>=10; var --) { printf("var: %d\n", var); if (var==99) { break; } } return 0; }
Output:
var: 100
var: 99
Example – Use of break statement in switch-case
[maxbutton id=”1″ url=”https://coderseditor.com/?id=174″ ]
#include <stdio.h> int main() { int num; printf("Enter value of num:"); scanf("%d",&num); switch (num) { case 1: printf("You have entered value 1\n"); break; case 2: printf("You have entered value 2\n"); break; case 3: printf("You have entered value 3\n"); break; default: printf("Input value is other than 1,2 & 3 "); } return 0; }
Output:
Enter value of num:1
You have entered value 1
Enter value of num:2
You have entered value 2
Enter value of num:3
You have entered value 3
Enter value of num:4
Input value is other than 1,2 & 3