Start learning free

LESSON 207 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Report Card V6 in Swift: 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:

let scores = [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 (print("Highest: \(highest)")).

Use .max()! / .min()! on a [Int] array; sum with a loop.

let scores = [92, 78, 85, 67, 74, 88, 91, 58]

let highest = scores.max()!
let lowest = scores.min()!
var total = 0
for score in scores {
    total += score
}
let average = total / scores.count

print("Highest: \(highest)")
print("Lowest: \(lowest)")
print("Average: \(average)")

STEP 1 OF 9
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Report Card V6 in Swift, explained

    Problem overview

    The program receives an array of class scores, [92, 78, 85, 67, 74, 88, 91, 58], and prints three statistics: the highest score, the lowest score, and the average rounded down. For this data the output is:

    Highest: 92
    Lowest: 58
    Average: 79
    

    The scores add up to 633 and there are 8 of them. The exact average is 79.125, and integer division drops the fraction, which gives 79.

    Approach: two library calls and one running total

    The highest and lowest scores need no loop, because arrays have max() and min() for this. The average needs the sum of all scores, so the program builds a running total: start at 0, visit every score once, add each to the total. Divide the total by the number of scores at the end.

    The three statistics are computed first, into constants, and printed afterwards. Keeping the calculation and the output apart makes each part easy to read and check.

    Step by step

    1. Find the highest score with scores.max()!. The call returns an optional, and the ! unwraps it.
    2. Find the lowest score the same way, with scores.min()!.
    3. Start a total as var total = 0. It is a var because it changes as scores are added.
    4. Loop over the scores with for score in scores, which hands you one value at a time rather than a position.
    5. Add each score to the total with total += score.
    6. Divide after the loop. total / scores.count is outside the loop, because it needs the finished sum.
    7. Print three lines, each made of a label, Highest: , Lowest: or Average: , and its value.

    The solution in Swift

    let scores = [92, 78, 85, 67, 74, 88, 91, 58]
    
    let highest = scores.max()!
    let lowest = scores.min()!
    var total = 0
    for score in scores {
        total += score
    }
    let average = total / scores.count
    
    print("Highest: \(highest)")
    print("Lowest: \(lowest)")
    print("Average: \(average)")
    

    Swift specifics worth knowing:

    • max() and min() return optionals. On an empty array there is no largest element, so the result is nil. For the array here the result is a real number, so ! is safe. On an empty array, max()! would stop the program with a run-time error.
    • for score in scores visits the values themselves. Earlier versions looped over indices because they needed positions to match two arrays. With one array and no need for positions, looping over the values is simpler.
    • += adds to a var in place: total += score means total = total + score.
    • Integer division. total and scores.count are both Int, so the quotient is an Int and the fraction is dropped: 633 divided by 8 is 79, not 79.125. Division in Swift truncates toward zero. For test scores, which are never negative, that is the same as rounding down.
    • scores.count is an Int. Swift's count is signed, so it can be divided into a total directly, with no conversion.

    Edge cases and common mistakes

    • An empty array. scores.max() and scores.min() are both nil and the count is 0. The solution would crash on max()!, and dividing by a count of 0 also stops the program. The lesson's data always has scores, so it doesn't guard against this; code that might receive an empty list should check scores.isEmpty first.
    • One score. With [100] the highest, lowest and average are all 100.
    • Fractions are dropped, not rounded. With [50, 51] the total is 101, the exact average is 50.5, and the program prints Average: 50.
    • Negative values. With [-5, 4, -2, 0] the total is -3, and -3 divided by 4 truncates toward zero, so the average is 0 rather than -1. Scores aren't negative, but it shows what the truncation does.
    • Dividing inside the loop. The division belongs after the loop. Inside it, the total isn't complete yet, and the value is recomputed on every pass.
    • Starting the total at the first score. The total starts at 0. Starting at scores[0] counts the first score twice.
    • Forgetting var. A let total can't be changed by +=; the total has to be a var.

    Testing

    These outputs come from running the solution on other arrays.

    scoresHighestLowestAverage
    [92, 78, 85, 67, 74, 88, 91, 58]925879
    [100]100100100
    [50, 51]515050
    [-5, 4, -2, 0]4-50

    Try an array in the editor above where the highest score comes first, and then one where it comes last, to check that the order of the scores doesn't matter.

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