Switch Case Definition
Switch Case Definition
1
How to switch and case statements work?
In switch statement when you are passed and integral argument then it searches the
case constant-expression within its body. If the integral value matches with the
case statement then control directly jump to the case statement and execute the
code until the end of the body or break statement, break statement transfer the
control out of the body.
In switch case, we can use the break statement to end the execution of the code for
the particular case. If we forgot to put the break statement after each case, the
program continues to the next case until not getting a break or end of the code.
2
Switch Statement Usage :
1. We can use switch statements alternative for an if..else ladder.
2. The switch statement is often faster than nested if...else Ladder.
3. Switch statement syntax is well structured and easy to understand.
There is one potential problem with the if-else statement which is the
complexity of the program increases whenever the number of alternative path
increases. If you use multiple if-else constructs in the program, a program might
become difficult to read and comprehend. Sometimes it may even confuse the
developer who himself wrote the program.
3
1. C program to read gender (M/F) and print corresponding gender
using switch.
#include <stdio.h>
int main()
{
char gender;
printf("Enter gender (M/m or F/f): ");
scanf("%c",&gender);
switch(gender)
{
case 'M':
case 'm':
printf("Male.");
break;
case 'F':
case 'f':
printf("Female.");
break;
default:
printf("Unspecified Gender.");
}
printf("\n");
return 0;
}
4
2. C program to find number of days in a month using switch case .
#include <stdio.h>
int main()
int month;
int days;
scanf("%d",&month);
switch(month)
case 4:
case 6:
case 9:
case 11:
days=30;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
5
days=31;
break;
case 2:
days=28;
break;
default:
days=0;
break;
if(days)
else
return 0;
}
6
3. C program to read weekday number and print weekday name using
switch.
int main()
int wDay;
scanf("%d",&wDay);
switch(wDay)
case 0:
printf("Sunday");
break;
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
7
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
default:
printf("\n");
return 0;
8
4. Write a program in C to accept a grade and display the equivalent
description.
Grade Description
E Excellent
V Very Good
G Good
A Average
F Fail
#include<stdio.h>
int main()
Char grd;
9
break;
case 'G':
strcpy(notes, " Good ");
break;
case 'A':
strcpy(notes, " Average");
break;
case 'F':
strcpy(notes, " Fails");
break;
default :
strcpy(notes, "Invalid Grade Found. \n");
break;
}
10