Break statement in C Language
In C programming language, break is a keyword that is used to terminate the loop or a case in the switch statement. It terminates the execution of the nearest enclosing of do, for, switch, or while statement in which it appears and control passes to the statement that follows the terminated statement. The break statement can be used in the following two scenarios:
- With loop - When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. In the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
- With switch case - The break statement also is used to terminate a case in the switch statement. When it is encountered in switch-case block, the control comes out of the switch-case.
// Program to find the length of a given string #include<stdio.h> #include<conio.h> void main() { int i,length=0; char string[100]; printf("Input a string : "); gets(string); for (i = 0; i < 100; i++) { if (string[i] == '\0') break; length++; } printf("\nThe length of the string is : %d \n",length); getch(); } Output : Input a string : Hello World The length of the string is : 11Break statement with switch case
// Program to find the length of a given string #include<stdio.h> #include<conio.h> void main() { int num1, num2; char key; printf("Input number 1 : "); scanf("%d\n",&num1) printf("Input number 2 : "); scanf("%d\n",&num2) printf("Input a operator : "); scanf("%c\n",&key) switch (key) { case '+': printf("Result : %d",num1+num2); break; case '-': printf("Result : %d",num1-num2); break; case '*': printf("Result : %d",num1*num2); break; default: printf("Invalid operator\n"); } getch(); } Output : Input number 1 : 15 Input number 2 : 10 Input a operator : - Result : 5
ADVERTISEMENT