Switch Statement in C
The switch statement allows us to execute a block of code among many alternatives.
It executes the statements associated with it.
it is used to perform different actions based on different conditions or cases.
Syntax
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
Program
#include <stdio.h>
int main()
{
char grade;
printf("Enter grade between A and E : ");
scanf("%c", &grade);
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
printf("Well done\n" );
break;
case 'C' :
printf("Very good\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'E' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade);
return 0;
}
Output 1
Enter grade between A and E : C
Very good
Your grade is C
Output 2
Enter grade between A and E : Z
Invalid grade
Your grade is Z
Join Our Social Media Connections
0 Comments