switch case in c

Switch case in c

switch is multi way conditional control statement. which allow to execute multiple operations for the different values.it help us to make choice on the number of alternatives. Here the syntax of switch statement is

switch(expression)
{
case constant1:
statement
………
case constant2:
statement
………
………
case constantn:
statement
………
default:
statement
………
}

in the above example switch, case and default are keywords. The expression following in the switch keyword can be integer or character expression. Then the constant expression in the case label should be of character or integer type. Every constant should be different from another (each case value should be different or unique) and we can not use float or string constant in case.multiple constant in a single case not allowed only one constant allow.In each case followed by any number of statements. The statements under any case can be any valid C statements like for, do-while, while, if-else etc or can give another switch statement inside switch, declare another switch statement inside switch statement is call nesting of switches

Let us take example how switch case works

/*program to understand the switch statement*/
#include<stdio.h>
int main()
{
int choice;
printf( ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Choice is one");
break; //optional
case 2:
printf("choice is two");
break; //optional
case 3:
printf("choice is three");
break; //optional
default: //optional
printf("wrong choice");
}
return 0;
}

let us discuss how switch statement works

firstly the switch control statement expression evaluated. if the expression value is matched with the case constant expression. Then the control transfer to the case label. but if the any case label not match with switch expression then control is transfer to the default label. The default label is optional. but in this example break keyword are used. break keyword is used to bring the program control out of the loop or block. so here is the example after execute any case label break keyword jump to the out of the switch statement. The break keyword can be use inside any loop, block etc

int a,b;
float x,y;
char ch;

Valid Switch Invalid switch valid case invalid case
switch(a) switch(x) case 10 case 12.9
switch(a+b) switch(x-2.8) case ‘A’ case a

#include<stdio.h>
int main()
{
int a=10,b=8,c=4;
switch( a> b & & c < b )
{
case 1:
printf("Welcome true 1");
break;
case 0: printf("Welcome false 0");
break;
default:
printf("Welcome true 1 and false 0");
}
return 0;
}