switch case for character
Switch Case for Character in C
In C, the switch
statement is used to perform different actions based on the value of a variable. It allows you to compare the value of a variable against multiple cases and execute the corresponding block of code for the matching case.
Here's an example of how to use the switch
statement with characters in C:
#include <stdio.h>
int main() {
char grade = 'A';
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good!\n");
break;
case 'C':
printf("Average!\n");
break;
case 'D':
printf("Below Average!\n");
break;
case 'F':
printf("Fail!\n");
break;
default:
printf("Invalid grade!\n");
}
return 0;
}
In this example, we have a variable grade
of type char
initialized with the value 'A'
. The switch
statement is used to compare the value of grade
against different cases.
- If
grade
is'A'
, the code inside thecase 'A':
block will be executed, and the output will be "Excellent!". - If
grade
is'B'
, the code inside thecase 'B':
block will be executed, and the output will be "Good!". - If
grade
is'C'
, the code inside thecase 'C':
block will be executed, and the output will be "Average!". - If
grade
is'D'
, the code inside thecase 'D':
block will be executed, and the output will be "Below Average!". - If
grade
is'F'
, the code inside thecase 'F':
block will be executed, and the output will be "Fail!". - If
grade
doesn't match any of the cases, the code inside thedefault:
block will be executed, and the output will be "Invalid grade!".
The break
statement is used to exit the switch
statement after executing the corresponding case. Without the break
statement, the execution would "fall through" to the next case, resulting in unexpected behavior.
Note that the switch
statement can only be used with integral types, such as char
, int
, or enum
. It cannot be used with floating-point types or strings.
I hope this explanation helps! Let me know if you have any further questions.