C programming tutorial
This statement is used to make decision from a number of choices.
switch( integer expression )
{
case constant 1:
//statements
break;
case constant 2:
//statements
break;
.
.
.
.
default:
//statements
}
integer expression after switch can be any expression that gives an integer as output.keyword case is followed by an integer or a charcter.
During execution of switch ,Firstly integer expression is evaluated.integer which comes as output of this expression is compared with constant following case keyword ,if constant matches with integer, program exeutes the statements following that case.If match is not found statements following keyword default are executed.
Suppose we have to write a program which asks user, which mathematical operation to perform and it prints the result after performing the desired mathematical operation.
#include<stdio.h>
main()
{
int a,b,c;
printf("Enter 1 to perform addition\n");
printf("Enter 2 to perform subtraction\n");
printf("Enter 3 to perform multiplication\n");
scanf("%d",&a); //User wll enter 1 to do addition 2 for subtraction and 3 for multiply
printf("Enter two numbers ");
scanf(%d",&b,&c);//b and c will store numbers on which operation to be performed
switch(a)
{
case 1:printf("%d",(b+c));
break;
case 2:printf("%d",(b-c));
break;
case 3:printf("%d",(b*c));
break;
default:printf("You entered wrong number");
}
}
Output of the program
Enter 1 to perform addition
Enter 2 to perform subtraction
Enter 3 to perform multiplication
2
Enter two numbers 5 5
0
suppose user wanted to perform subtraction.He will input 2 to perform subtraction.this 2 will be stored in a.Then program will ask for two numbers on which desired operation to be performed,These two numbers will be stored in b and c.
switch statement will compare 'a' with constants after keyword case.Since a is 2 hence statement following case 2 will be execute.It will print b-c;
Note:If we wll not write break statement in switch case then switch executes the case where a match is found and all subsequent cases and default as well.