In this easy C language tutorial, we will learn everything about switch case statement in C programming, how to use and where to use a switch case.
Some times, a variable can have more than one values, and each value needs to execute different statements. For example,
Syntax:
switch(expression)
{
case value_1:
//statements
break;
case value_2:
//statements
break;
case value_3:
//statements
break;
default:
//statements
}
Example 1: switch case example in c, to print week day.
#include<stdio.h>
int main()
{
int day;
printf("\nEnter Weeknum");
scanf("%d", &day);
switch(day)
{
case 1:
printf("\nSunday");
break;
case 2:
printf("\nMonday");
break;
case 3:
printf("\nTuesday");
break;
case 4:
printf("\nWednesday");
break;
case 5:
printf("\nThursday");
break;
case 6:
printf("\nFriday");
break;
case 7:
printf("\nSaturday");
break;
default:
printf("\nWrong Choice");
}
return 0;
}
Sample Output:Enter Weeknum : 3
Tuesday
Rules for Switch Case Statement in C
the swi tch statement allows a variable to be tested, with the list of values, called the case.- the switch statement can have any number of case.
- All case must end with a colon ( : ).
- switch, only accept int or char variable as a parameter.
- float and text values are not allowed.
- If, no case value is matched than default is executed.
- the default is optional, you can skip in your program.
- the break is to end processing and exit from the switch.
Example 2: C program, to accept an alphabet, and check it is vowel or consonant.
#include<stdio.h>
int main()
{
char alph;
printf("\nEnter an Alphabet");
scanf("%c", &alph);
switch(alph)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("\nVowel");
break;
default:
printf("\nConsonant");
}
return 0;
}
Sample Output:Enter an Alphabet : A
Vowel