Start learning free

LESSON 207 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Report Card V4 in Rust: Grades for Several Students

Practice Read the full explanation

Combine lists, loops, and conditionals to print a letter grade for each student in a class.

You start with:

// Rust: the editor starts empty - declare the data yourself, for example:
let names = vec!["Alice", "Bob", "Carol", "Dan"];
let scores = vec![92, 78, 85, 67];

Build:

Alice: A
Bob: C
Carol: B
Dan: D

Rules:

  • Loop over the indices of the students (0..names.len()) so you can read the name and the score at the same position.
  • Use the same scale as V3: 90+ A, 80-89 B, 70-79 C, 60-69 D, below 60 F.
  • On each iteration print the name, a colon and a space, then the grade, for example Alice: A.

Use Vec<&str> and Vec<i32> with index loops.

let names = vec!["Alice", "Bob", "Carol", "Dan"];
let scores = vec![92, 78, 85, 67];
for i in 0..names.len() {
    let score = scores[i];
    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!("{}: {}", names[i], grade);
}

STEP 1 OF 11
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Report Card V4 in Rust, explained

    Problem overview

    A class has four students, and their names and scores sit in two vectors: names holds Alice, Bob, Carol and Dan, and scores holds 92, 78, 85 and 67. The score at position 0 belongs to the name at position 0, and so on. The program prints one line for each student with a letter grade:

    Alice: A
    Bob: C
    Carol: B
    Dan: D
    

    The scale is the one from the previous version: 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. What is new here is that the same decision is made once per student, inside a loop.

    Approach: one index, two vectors

    Rust has no built-in link between the two vectors, so the program connects them by position. A loop counts i from 0 up to, but not including, names.len(). For each i, names[i] is the student and scores[i] is that student's score.

    Inside the loop the program picks a grade with the same if/else-if ladder as before, checking from the top grade down so each later test needs only a lower bound. Then it prints the name and the grade. Because the print is inside the loop, it runs once per student, which produces the four lines.

    One new Rust feature appears: let grade; with no value. The variable is declared first and given its value later, in the ladder. This works without mut because each pass through the loop creates a new grade, and the ladder assigns it exactly once.

    Step by step

    1. Create names with vec!, in the order Alice, Bob, Carol, Dan.
    2. Create scores with 92, 78, 85 and 67, in the same order so the positions line up.
    3. Start the loop with for i in 0..names.len(). The range excludes its end, so i takes the values 0, 1, 2 and 3.
    4. Read the score at position i into score, so the ladder tests a short name.
    5. Declare grade without a value. The ladder will fill it in.
    6. Open the ladder with an if for 90 or more, assigning "A".
    7. Add else if for 80 or more, assigning "B".
    8. Add else if for 70 or more, assigning "C".
    9. Add else if for 60 or more, assigning "D".
    10. Close with else, assigning "F". With this branch, every path gives grade a value.
    11. Print inside the loop, after the ladder, the name at position i, a colon and a space, and the grade, using two {} placeholders.

    The solution in Rust

    let names = vec!["Alice", "Bob", "Carol", "Dan"];
    let scores = vec![92, 78, 85, 67];
    for i in 0..names.len() {
        let score = scores[i];
        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!("{}: {}", names[i], grade);
    }
    

    Rust details worth knowing:

    • Indexes are usize. The range 0..names.len() produces usize values, which is what vector indexing requires. An i32 variable can't index a vector: names[i] with i: i32 is a compile error saying the slice cannot be indexed by i32.
    • Delayed initialization. The compiler checks that every path reaches an assignment before grade is used. If the final else is removed, the program doesn't compile: the error reads used binding `grade` is possibly-uninitialized.
    • Out-of-range indexing panics. A vector gives no default value for a missing position. Reading past the end stops the program with index out of bounds.
    • Element types. scores becomes a Vec<i32>, because the comparisons with literals don't say otherwise and i32 is the default integer type. names is a Vec<&str>.

    Complexity

    Time: O(n) for n students. The loop visits each position once, and each visit does a fixed number of comparisons. Space: O(1) extra, apart from the two input vectors, because the loop keeps only i, score and grade.

    Edge cases and common mistakes

    • Boundaries. For scores 90, 59 and 60, the program prints A, F and D.
    • No students. With two empty vectors the range 0..0 is empty, so the loop doesn't run and nothing is printed.
    • A vector that is too short. With two names and only one score, the first line prints Ann: A and the second pass panics with index out of bounds: the len is 1 but the index is 1. The loop follows names.len(), so the vectors must have the same length.
    • Looping one step too far. 0..=names.len() includes the length itself, and names[names.len()] panics with index out of bounds. Use the half-open range 0..names.len().
    • Printing outside the loop. A print after the closing brace wouldn't compile, because grade and i exist only inside the loop. The print has to sit in the loop body to run once per student.
    • Mixing up the vectors. Writing names[i] where the score belongs gives a type error at compile time, since a name is text and the comparison needs a number.

    Testing

    • The lesson's data prints Alice: A, Bob: C, Carol: B and Dan: D, one per line.
    • Names Eve, Finn and Gus with scores 90, 59 and 60 print Eve: A, Finn: F and Gus: D.
    • Two empty vectors print 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