switch statement in c

switch statements is used, when there is multiple alternatives but only one needs to be selected. However, the complexity of such programs increases dramatically, when the number of alternatives increases, then the programs becomes difficult to read and follow. C built a multi-way decision statement known as “switch statement” . It is like if else-if ladder statement.

syntax:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

rules for switch statement:

  • the switch expression must be a character type or integer type
  • the case value must be inter or character
  • the case value can be used only inside switch function
  • The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.
  • break is not mandatory for default statement

flowchart:

Switch statement in c

example:

#include
int main()
{
int i;
float a,b;
clrscr();
printf("\nEnter any no.s a & b: ");
scanf("%f%f",&a,&b);
printf("\n\n 1. ADDITION\n\n 2. SUBTRACTION\n\n 3. MULTIPLICATION\n\n
4. DIVISION ");
printf("\n\n Enter your option: ");
scanf("%d",&i);
switch(i)
{
case 1:
case 2:
printf("\n\n%f + %f = %f",a,b,a+b);
break;
printf("\n\n%f - %f = %f",a,b,a-b);
break;
case 3:
case 4:
printf("\n\n%f * %f = %f",a,b,a*b);
break;
if(b!=0)
printf("\n\n%f / %f = %f",a,b,a/b);
else
default :
}
printf("\nDivision is not possible with zero");
break;
printf("\n Enter correct option");
scanf("%d",&i);
return 0;
}

output:

Enter any no.s a & b: 45 15
1. ADDITION
2. SUBTRACTION
3. MULTIPLICATION
4. DIVISION
Enter your option: 4
45.000000 / 15.000000 = 3.000000