How to get a grade and transform it into a letter grade in C#

2 Answers

0 votes
using System;

class Program
{
    public string ToLetterGrade(double score) {
        var tpl = new Tuple<double, string>[] {
            new Tuple<double, string>(95.0, "A+"),
            new Tuple<double, string>(90.0, "A"),
            new Tuple<double, string>(85.0, "B+"),
            new Tuple<double, string>(80.0, "B"),
            new Tuple<double, string>(75.0, "C+"),
            new Tuple<double, string>(70.0, "C"),
            new Tuple<double, string>(65.0, "D+"),
            new Tuple<double, string>(60.0, "D")
        };

        int tpl_Length = tpl.Length;
        for (int i = 0; i < tpl_Length; i++) {
            if (score >= tpl[i].Item1) {
                return tpl[i].Item2;
            }
        }

        return "F";
    }

    static void Main()
    {
        Console.WriteLine(new Program().ToLetterGrade(95)); 
        Console.WriteLine(new Program().ToLetterGrade(90)); 
        Console.WriteLine(new Program().ToLetterGrade(80)); 
        Console.WriteLine(new Program().ToLetterGrade(60)); 
        Console.WriteLine(new Program().ToLetterGrade(50)); 
    }
}

 
/*
run:
     
A+
A
B
D
F
 
*/

 



answered Mar 23, 2025 by avibootz
edited Mar 23, 2025 by avibootz
0 votes
using System;

public class Program
{
    public string ToLetterGrade(double score)
    {
        // Define scores and grades
        double[] scores = {95.0, 90.0, 85.0, 80.0, 75.0, 70.0, 65.0, 60.0};
        string[] grades = {"A+", "A", "B+", "B", "C+", "C", "D+", "D"};

        // Iterate through scores and find the grade
        int scores_Length = scores.Length;
        for (int i = 0; i < scores_Length; i++) {
            if (score >= scores[i]) {
                return grades[i];
            }
        }

        return "F"; // Default grade if none of the scores match
    }

    public static void Main(string[] args)
    {
        Program program = new Program();

        // Test the program with individual scores
        Console.WriteLine(program.ToLetterGrade(95)); // A+
        Console.WriteLine(program.ToLetterGrade(90)); // A
        Console.WriteLine(program.ToLetterGrade(80)); // B
        Console.WriteLine(program.ToLetterGrade(60)); // D
        Console.WriteLine(program.ToLetterGrade(50)); // F
    }
}


 
/*
run:
     
A+
A
B
D
F
 
*/

 



answered Mar 23, 2025 by avibootz

Related questions

2 answers 254 views
1 answer 176 views
1 answer 199 views
1 answer 190 views
1 answer 209 views
2 answers 243 views
...