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
- Find the highest score with
scores.max()!. The call returns an optional, and the!unwraps it. - Find the lowest score the same way, with
scores.min()!. - Start a total as
var total = 0. It is avarbecause it changes as scores are added. - Loop over the scores with
for score in scores, which hands you one value at a time rather than a position. - Add each score to the total with
total += score. - Divide after the loop.
total / scores.countis outside the loop, because it needs the finished sum. - Print three lines, each made of a label,
Highest:,Lowest:orAverage:, 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()andmin()return optionals. On an empty array there is no largest element, so the result isnil. 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 scoresvisits the values themselves. Earlier versions looped overindicesbecause they needed positions to match two arrays. With one array and no need for positions, looping over the values is simpler.+=adds to avarin place:total += scoremeanstotal = total + score.- Integer division.
totalandscores.countare bothInt, so the quotient is anIntand 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.countis anInt. Swift'scountis signed, so it can be divided into a total directly, with no conversion.
Edge cases and common mistakes
- An empty array.
scores.max()andscores.min()are bothniland the count is 0. The solution would crash onmax()!, 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 checkscores.isEmptyfirst. - 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 printsAverage: 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. Alettotal can't be changed by+=; the total has to be avar.
Testing
These outputs come from running the solution on other arrays.
| scores | Highest | Lowest | Average |
|---|---|---|---|
[92, 78, 85, 67, 74, 88, 91, 58] | 92 | 58 | 79 |
[100] | 100 | 100 | 100 |
[50, 51] | 51 | 50 | 50 |
[-5, 4, -2, 0] | 4 | -5 | 0 |
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.
