Objective
Write a C# program to display the text grade corresponding to a given numerical grade, using the following equivalence:
9,10 = Excellent
7,8 = Very good
6 = Good
5 = Pass
0-4 = Fail
Your program should ask the user for a numerical grade and display the corresponding text grade. You should do this twice: first using "if" and then using "switch".
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace which contains fundamental classes
class Program // Define the Program class
{
static void Main() // The entry point of the program
{
// Ask the user to enter a numerical grade
Console.Write("Enter the numerical grade: ");
int grade = int.Parse(Console.ReadLine()); // Read and convert the input into an integer
// Using 'if' to determine the corresponding grade text
if (grade >= 9 && grade <= 10) // Check if grade is between 9 and 10 (inclusive)
{
Console.WriteLine("Excellent"); // Display "Excellent" for grades 9-10
}
else if (grade >= 7 && grade <= 8) // Check if grade is between 7 and 8 (inclusive)
{
Console.WriteLine("Very good"); // Display "Very good" for grades 7-8
}
else if (grade == 6) // Check if grade is exactly 6
{
Console.WriteLine("Good"); // Display "Good" for grade 6
}
else if (grade == 5) // Check if grade is exactly 5
{
Console.WriteLine("Pass"); // Display "Pass" for grade 5
}
else if (grade >= 0 && grade <= 4) // Check if grade is between 0 and 4 (inclusive)
{
Console.WriteLine("Fail"); // Display "Fail" for grades 0-4
}
else // If none of the above conditions are met, the grade is invalid
{
Console.WriteLine("Invalid grade"); // Display "Invalid grade" for any invalid input
}
// Separate the two sections with a line break
Console.WriteLine();
// Using 'switch' to determine the corresponding grade text
switch (grade) // Switch statement based on the value of 'grade'
{
case int n when (n >= 9 && n <= 10): // Check if grade is between 9 and 10 (inclusive)
Console.WriteLine("Excellent"); // Display "Excellent" for grades 9-10
break; // Exit the switch block after executing this case
case int n when (n >= 7 && n <= 8): // Check if grade is between 7 and 8 (inclusive)
Console.WriteLine("Very good"); // Display "Very good" for grades 7-8
break; // Exit the switch block after executing this case
case 6: // Check if grade is exactly 6
Console.WriteLine("Good"); // Display "Good" for grade 6
break; // Exit the switch block after executing this case
case 5: // Check if grade is exactly 5
Console.WriteLine("Pass"); // Display "Pass" for grade 5
break; // Exit the switch block after executing this case
case int n when (n >= 0 && n <= 4): // Check if grade is between 0 and 4 (inclusive)
Console.WriteLine("Fail"); // Display "Fail" for grades 0-4
break; // Exit the switch block after executing this case
default: // This block executes if no case matches
Console.WriteLine("Invalid grade"); // Display "Invalid grade" for any invalid input
break; // Exit the switch block after executing this case
}
}
}