When break is encountered, the loop is terminated and the control goes to the next statement after the loop. Break is used in switch case to exit the switch-case after a specific match for the case is met with. If no case is matched, then the default statement is executed. If no break is used then once the case is matched, all the rest of the cases thereafter will get executed.
#include<stdio.h>
#include<conio.h>
void main() {
int var;
clrscr();
printf("Enter a value");
scanf("%d", &var);
switch(var)
{
case 1:
printf("Number is less than 5");
case 2:
printf("Number is less than 15");
default:
printf("Number is more than 25");
}
getch();
}
If the user inputs 1, the case matching the value 1 for var, is executed. However since there is no break, the statements corresponding to all the cases there after including the default will be displayed.
If break is used, only the statement matching the particular case will get executed.
Eg:
#include<stdio.h>
#include<conio.h>
void main() {
int var;
clrscr();
printf("Enter a value");
scanf("%d",&var);
switch(var)
{
case 1:
printf("\nNumber is less than 5");
break;
case 2:
printf("\nNumber is less than15");
break;
default:
printf("\nNumber is more than 25");
break;
}
getch();
}
If we input the value 1 for var, for the above program, only Number less than 5 for the case 1 will get executed.
0 Comments