Summary: This C program takes a student's percentage score as input and determines their grade using a switch-case statement. The program divides the score by 10 to map it to a single-digit value, making it easier to categorize grades. It also includes error handling for invalid input values.
#include <stdio.h>
int main() {
int score;
// Taking input from the user
printf("Enter the student's percentage score: ");
scanf("%d", &score);
// Using switch-case to determine the grade, including handling invalid input
switch (score / 10) {
case 10:
case 9:
printf("Grade A\n");
break;
case 8:
printf("Grade B\n");
break;
case 7:
printf("Grade C\n");
break;
case 6:
printf("Grade D\n");
break;
case 5:
printf("Grade E\n");
break;
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Fail\n");
break;
default:
printf("Invalid Input. Score must be between 0 and 100.\n");
break;
}
return 0;
}
Why is the score divided by 10?
The score is divided by 10 (`score / 10`) to simplify the grading logic. Instead of checking multiple individual conditions (e.g., if score >= 90, if score >= 80, etc.), we convert the score into a single-digit integer (0-10). This allows us to map a range of scores to a single case in the switch statement, making the program more concise and readable.
Why use switch-case instead of if-else?
A `switch-case` statement is more efficient and easier to read when dealing with multiple discrete conditions like these grade categories. Instead of writing multiple `if-else` conditions, the switch statement directly maps the computed single-digit value to a corresponding grade.
Why use break statements?
The `break` statement ensures that once a matching case is found, execution stops and exits the switch block. Without `break`, execution would continue into subsequent cases, leading to incorrect results.
Why does the default case exist?
The `default` case acts as a catch-all condition. If the user inputs an invalid score (less than 0 or greater than 100), it prints an error message instead of proceeding with an incorrect grade calculation. This ensures that only valid scores are processed.