Below I have written a program to evaluate a letter grade and print a message based on how well the score is. Let's say I wanted to get that information from the user input, how would I be able to accept both lower and upper case letters?
#include <stdio.h>
int main (){
/* local variable definition */
char grade = 'B';
if (grade == 'A'){
printf("Excellent!\n");
}
else if (grade == 'B' || grade == 'C'){
printf("Well done\n");
}
else if (grade == 'D'){
printf("You passed\n" );
}
else if (grade == 'F'){
printf("Better try again\n" );
}
else {
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
how would i be able to accept both lower and upper case letters?
You want to normalize grade
using toupper()
before performing the checks.
You can also use a switch()
statement like
switch(toupper(grade)) {
case 'A':
// ...
break;
case 'B':
case 'C': // Match both 'B' and 'C'
// ...
break;
}
The harder way is to check for lower case as well:
if (grade == 'A' || grade == 'a'){
// ...
}
else if (grade == 'B' || grade == 'b' || grade == 'C' || grade == 'c'){
// ...
}
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With