Start learning free

LESSON 209 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Report Card V6 in Rust: Highest, Lowest and Average

Practice Read the full explanation

Compute three class statistics from a list of scores: the highest, the lowest, and the average.

You start with:

// Rust: the editor starts empty - declare the data yourself, for example:
let mut scores = vec![92, 78, 85, 67, 74, 88, 91, 58];

Build:

Highest: 92
Lowest: 58
Average: 79

Rules:

  • highest is the largest value in scores.
  • lowest is the smallest value in scores.
  • average is the sum of all scores divided by how many there are, rounded down (integer division).
  • Print "Highest: ", "Lowest: " and "Average: " on three lines, in the order of the sample output (println!("Highest: {}", highest);).

Use .iter().max() and .iter().min() which return Option; .iter().sum() for the total.

let mut scores = vec![92, 78, 85, 67, 74, 88, 91, 58];
let mut highest = scores.iter().max().unwrap();
let mut lowest = scores.iter().min().unwrap();
let mut total = 0;
for s in &scores {
    total += s;
}
let mut average = total / scores.len();
println!("Highest: {}", highest);
println!("Lowest: {}", lowest);
println!("Average: {}", average);

STEP 1 OF 10
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Report Card V6 in Rust, explained

    Problem overview

    The last version of the report card looks at a whole class. A vector holds eight scores: 92, 78, 85, 67, 74, 88, 91 and 58. The program prints the highest score, the lowest score and the average, rounded down:

    Highest: 92
    Lowest: 58
    Average: 79
    

    The scores add up to 633, and 633 divided by 8 is 79.125. Integer division drops the part after the point, so the average is 79. The previous versions graded individual scores; this one summarizes a list of them.

    Approach: iterators for the extremes, a loop for the sum

    The highest and lowest scores come from iterator methods. scores.iter() walks the vector, max() returns the biggest element and min() the smallest. Each returns an Option, because an empty vector has no biggest element, so unwrap() takes the value out of the Some.

    The average needs a sum. A running total starts at 0, and a loop adds each score to it. After the loop, the total divided by the number of scores, scores.len(), is the average. Both numbers are integers, so the division truncates.

    That makes three separate passes over the data: one for max, one for min and one for the sum. For a list this size the cost is irrelevant, and each pass says exactly what it does.

    Step by step

    1. Create scores with vec! and the eight values in the given order.
    2. Find highest with scores.iter().max().unwrap().
    3. Find lowest in the same way with min().
    4. Create total as let mut, starting at 0. A running total begins at zero, before any score is counted.
    5. Loop over the scores with for s in &scores. The & borrows the vector, so it is still available after the loop.
    6. Add each score to total inside the loop.
    7. Compute average after the loop as total / scores.len().
    8. Print the three lines in the order Highest, Lowest, Average, each with a {} placeholder.

    The solution in Rust

    let mut scores = vec![92, 78, 85, 67, 74, 88, 91, 58];
    let mut highest = scores.iter().max().unwrap();
    let mut lowest = scores.iter().min().unwrap();
    let mut total = 0;
    for s in &scores {
        total += s;
    }
    let mut average = total / scores.len();
    println!("Highest: {}", highest);
    println!("Lowest: {}", lowest);
    println!("Average: {}", average);
    

    Rust details worth knowing:

    • Extra muts. Only total changes after it is created. The other variables are marked mut in the lesson's code, and the compiler answers with variable does not need to be mutable warnings. They are only warnings, and the program prints the expected three lines.
    • The element type is usize. The division total / scores.len() needs both sides to be the same type, and len() returns a usize. Rust therefore infers usize for total and for the elements of scores. One result is that a negative score doesn't compile: vec![92, -5] in this program fails with the trait bound `usize: Neg` is not satisfied.
    • References to elements. max() and min() on iter() return Option<&usize>, so highest and lowest are references into the vector. println! prints through the reference, so the output is the plain number. For the same reason s in the loop is a &usize, and total += s compiles because Rust can add a reference to an integer in place.
    • unwrap() panics on None. It is safe here because the vector has eight elements.
    • Integer division. 633 / 8 gives 79 in integer arithmetic. The number 79.125 would need f64 values.

    Complexity

    Time: O(n) for n scores. max(), min() and the summing loop each walk the vector once, which is three passes, and three passes are still O(n). Space: O(1) extra, because the program keeps a few single values, and the references point into the existing vector.

    Edge cases and common mistakes

    • An empty vector. max() returns None, so unwrap() panics with called `Option::unwrap()` on a `None` value. Past that point, dividing by scores.len(), which is 0, would panic with attempt to divide by zero.
    • One score. A vector holding only 70 gives a highest, lowest and average of 70.
    • Averages that don't divide evenly. Scores 90 and 91 have a total of 181, and the average is 90. The remainder is dropped, not rounded to the nearest whole number.
    • Starting the total at something other than 0. Any other starting value would be added to every average.
    • Dividing inside the loop. The division must come after the loop, once the total is complete.
    • Forgetting the &. for s in scores moves the vector into the loop, and the later call to scores.len() is then an error.

    Testing

    • The lesson's data prints Highest: 92, Lowest: 58 and Average: 79.
    • A single score of 70 prints 70 on all three lines.
    • Scores 90 and 91 print Highest: 91, Lowest: 90 and Average: 90.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free