Start learning free

LESSON 208 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in Rust: Grades by Subject with BTreeMap

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:

// Rust: the editor starts empty - declare the data yourself, for example:
let mut grades = BTreeMap::new();
grades.insert("Math", 92);
grades.insert("English", 78);
grades.insert("Science", 85);
grades.insert("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 BTreeMap<&str, i32> - it stores keys in sorted order.

let mut grades = BTreeMap::new();
grades.insert("Math", 92);
grades.insert("English", 78);
grades.insert("Science", 85);
grades.insert("History", 67);
for (subject, score) in &grades {
    let 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";
    }
    println!("{}: {}", subject, grade);
}

STEP 1 OF 11
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in Rust, explained

    Problem overview

    This version stores a student's scores by subject. Instead of two vectors lined up by position, a dictionary maps each subject name to its score: Math 92, English 78, Science 85 and History 67. The program prints each subject with its letter grade, in alphabetical order of the subject:

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

    The scale is the familiar one: 90 or more is an A, 80 to 89 a B, 70 to 79 a C, 60 to 69 a D, and below 60 an F. The previous version looped over a vector by position. Here the loop walks the dictionary itself.

    Approach: a map that keeps its keys sorted

    Rust's dictionary types are HashMap and BTreeMap, both in std::collections. A HashMap visits its entries in an unspecified order that can differ from one run to the next, so it can't promise alphabetical output. A BTreeMap keeps its keys sorted, and iterating over it yields the entries in key order. For text keys the order is alphabetical, which is exactly what the output needs, with no sorting step in the program.

    The program inserts the four subjects in the order Math, English, Science, History. Insertion order doesn't matter: the map puts them in order itself. A loop over the map then gives each subject together with its score, and the loop body is the grading ladder from before, checking from the top grade down.

    The first entry the loop reaches is English, whose score is 78. The test for 90 fails, then 80 fails, then 70 succeeds, so English gets a C. The loop moves on to History (67, a D), Math (92, an A) and Science (85, a B). That matches the four lines above.

    Step by step

    1. Create the map with let mut grades = BTreeMap::new();. It needs mut because inserting changes it.
    2. Insert Math and English with insert, which takes the key first and the value second.
    3. Insert Science and History the same way.
    4. Loop over the map with for (subject, score) in &grades. The pair pattern splits each entry into its key and value, and the & borrows the map so it is still usable after the loop.
    5. Declare grade without a value inside the loop. The ladder will assign it.
    6. Open the ladder with if *score >= 90, assigning "A".
    7. Add the else if branches for 80, 70 and 60, assigning "B", "C" and "D".
    8. Close with else, assigning "F", so every path sets grade.
    9. Print inside the loop the subject, a colon and a space, and the grade. That gives one line per subject.

    The solution in Rust

    let mut grades = BTreeMap::new();
    grades.insert("Math", 92);
    grades.insert("English", 78);
    grades.insert("Science", 85);
    grades.insert("History", 67);
    for (subject, score) in &grades {
        let 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";
        }
        println!("{}: {}", subject, grade);
    }
    

    Rust details worth knowing:

    • The import. BTreeMap lives in std::collections, and a program that names it needs use std::collections::BTreeMap; at the top of the file. Without it the compiler reports use of undeclared type `BTreeMap`.
    • Inferred types. The map's types come from the inserts: keys are &str and values are i32. Nothing is annotated.
    • Why *score. Looping over &grades yields references: score is an &i32, not an i32. Writing score >= 90 is a type error (mismatched types, because a reference is compared with a number). The * reads the number behind the reference.
    • Borrowing keeps the map alive. Looping over grades without the & moves the map into the loop, and using it afterwards is an error (borrow of moved value: `grades`). With &grades the map can still be used after the loop.
    • Key order is byte order. Strings compare byte by byte, so every uppercase letter sorts before every lowercase one. A map with the keys art, Zoology and Biology iterates as Biology, Zoology, art.

    Complexity

    Time: O(n log n) for n subjects in total. Each insert into a BTreeMap costs O(log n), and the loop that follows visits each entry once in O(n). The grading itself takes constant time per entry. Space: O(n) for the map.

    Edge cases and common mistakes

    • Inserting a key twice. A second insert with the same key replaces the value. After grades.insert("Math", 50), insert returns Some(92), the old value, and grades.get("Math") gives Some(50). The map still has four subjects.
    • An empty map. The loop body never runs and nothing is printed.
    • A missing key. grades.get("Art") returns None and doesn't panic, because lookups on a map give an Option.
    • Boundaries. A score of exactly 90 is an A and 59 is an F. The ladder uses >=, so each boundary belongs to the higher grade.
    • Using a HashMap by habit. The code would look almost the same, but the lines could come out in a different order each time the program runs, and the lesson's tests expect the alphabetical order.
    • Expecting insertion order. The output starts with English, although Math was inserted first. Sorted key order is the whole point of this map type.

    Testing

    • The lesson's data prints English: C, History: D, Math: A and Science: B.
    • An empty BTreeMap prints nothing.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free