Start learning free

LESSON 204 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in C#: Grades from a SortedDictionary

Practice Read the full explanation

Use a dictionary, a loop, and conditionals to print each subject with its letter grade in alphabetical order.

You start with:

SortedDictionary<string, int> grades = new SortedDictionary<string, int>();
grades["Math"] = 92;
grades["English"] = 78;
grades["Science"] = 85;
grades["History"] = 67;

Build:

English: C
History: D
Math: A
Science: B

Rules:

  • Visit the subjects in alphabetical order.
  • Look up each subject's score in the dictionary and apply the grading scale (90+ A, 80s B, 70s C, 60s D, else F).
  • On each iteration print the subject, a colon and a space, then the grade, for example English: C.

Use a SortedDictionary - it iterates its keys in sorted order automatically.

SortedDictionary<string, int> grades = new SortedDictionary<string, int>();
grades["Math"] = 92;
grades["English"] = 78;
grades["Science"] = 85;
grades["History"] = 67;

foreach (string subject in grades.Keys) {
    int score = grades[subject];
    string grade;
    if (score >= 90) {
        grade = "A";
    } else if (score >= 80) {
        grade = "B";
    } else if (score >= 70) {
        grade = "C";
    } else if (score >= 60) {
        grade = "D";
    } else {
        grade = "F";
    }
    Console.WriteLine(subject + ": " + grade);
}

STEP 1 OF 9
    Ctrl + Enter to check

    C# · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in C#, explained

    Problem overview

    In this version the data is no longer two parallel arrays. A SortedDictionary<string, int> named grades maps each subject to the student's score in it: Math 92, English 78, Science 85 and History 67. The program must print each subject with its letter grade, in alphabetical order of subject, using the usual scale: 90 and above is A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, and below 60 is F.

    The subjects were added in the order Math, English, Science, History, but the output is sorted:

    English: C
    History: D
    Math: A
    Science: B

    Approach: loop over the keys, look up each score

    A dictionary stores key and value pairs. To visit every subject, loop over grades.Keys, the collection of keys. For each key you read the value with grades[subject], which gives the score stored under that subject name.

    The order of the output comes from the type of the dictionary. A SortedDictionary keeps its keys sorted at all times, so grades.Keys comes out from A to Z whatever the order of insertion. The loop therefore needs no sorting code. A plain Dictionary makes no promise about enumeration order, so it would not be a safe choice when the order of the output matters.

    Inside the loop the work is the same as in the previous version: read the score, run the grade ladder, print one line. The only change is where the score comes from, the dictionary lookup in place of an array position.

    Step by step

    1. Loop over the keys. foreach (string subject in grades.Keys) gives subject a new key on each pass, from English to Science.
    2. Look up the score. int score = grades[subject]; reads the value stored under the current key.
    3. Declare grade as a string with no value yet.
    4. Start the ladder with if (score >= 90) and assign "A". The tests run from the top grade down, so later tests only need a lower bound.
    5. Add the else if branches for 80 (B), 70 (C) and 60 (D). Each is reached only when the earlier ones failed.
    6. End with else for the F, so that every score assigns a grade.
    7. Print inside the loop, after the ladder: subject + ": " + grade. One line per subject gives the four lines of output.

    Tracing the sorted order: the first key is English, whose score is 78. The ladder fails the 90 and 80 tests, passes the 70 test, and the program prints English: C. History follows with 67 and gets a D, then Math with 92 gets an A, and Science with 85 gets a B.

    The solution in C#

            SortedDictionary<string, int> grades = new SortedDictionary<string, int>();
            grades["Math"] = 92;
            grades["English"] = 78;
            grades["Science"] = 85;
            grades["History"] = 67;
    
            foreach (string subject in grades.Keys) {
                int score = grades[subject];
                string grade;
                if (score >= 90) {
                    grade = "A";
                } else if (score >= 80) {
                    grade = "B";
                } else if (score >= 70) {
                    grade = "C";
                } else if (score >= 60) {
                    grade = "D";
                } else {
                    grade = "F";
                }
                Console.WriteLine(subject + ": " + grade);
            }
    

    Details worth knowing:

    • The indexer both adds and replaces. grades["Math"] = 92; adds the key when it is new and overwrites the value when it exists. grades.Add("Math", 1) on an existing key throws an ArgumentException instead.
    • Reading a missing key throws. grades["Music"] throws a KeyNotFoundException when there is no such key. Use ContainsKey or TryGetValue when a key may be absent: TryGetValue returns false and gives 0 in its out variable for a missing key. Inside this lesson's loop the key always exists, because it comes from the dictionary itself.
    • Keys are unique. Assigning to the same subject twice leaves one entry, holding the last value.
    • Do not change the dictionary during the loop. Adding or removing entries inside a foreach over its keys makes the next step of the loop throw an InvalidOperationException. The lesson only reads, so it is safe.
    • The type has two type arguments. SortedDictionary<string, int> says keys are strings and values are int, which is why grades[subject] can be stored directly in an int.

    Edge cases and common mistakes

    • Expecting insertion order. The subjects were inserted in a different order from the output. The sorted order is a property of SortedDictionary.
    • Looping over grades directly. Looping over the dictionary itself gives KeyValuePair items, not strings. That also works, with pair.Key and pair.Value, but the lesson loops over grades.Keys and looks up each value.
    • Adding a subject. If you add grades["Art"] = 59; before the loop, the program prints Art: F as the first line, because Art sorts before English. With grades["Math"] = 100; added, Math still gets an A and still stays between History and Science.
    • Boundary scores. A score of exactly 90 is an A and 59 is an F, so the tests use >=.
    • Empty dictionary. With no subjects the loop never runs and nothing is printed.

    Testing

    • The starting data prints English: C, History: D, Math: A and Science: B.
    • Adding grades["Art"] = 59; and setting Math to 100 prints five lines, starting with Art: F, then English, History, Math and Science, with Math still an A.

    The next version builds on this one.

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free