Problem overview
The last version of the project computes class statistics. From a list of scores the program prints the highest score, the lowest score and the average, rounded down. The starter code is one line:
val scores = listOf(92, 78, 85, 67, 74, 88, 91, 58)
The highest is 92 and the lowest is 58. The eight scores add up to 633, and 633 divided by 8 is 79.125, so with integer division the average is 79:
Highest: 92
Lowest: 58
Average: 79
Approach
There are three small jobs. The highest and the lowest values are built into Kotlin's collections: scores.max() and scores.min() each return the answer in a single call, so no loop is needed for them.
The average needs a total, and the lesson adds it up by hand with a loop. Start a counter at 0, add every score to it, and when the loop ends divide by the number of scores. Both sides of the division are Int, so the result drops the fraction, as in the first versions of the project.
Step by step
- Highest. Declare
val highest = scores.max(). The list was made withlistOf, so it is read-only, but reading its biggest element is fine. - Lowest. Declare
val lowest = scores.min(), the mirror of the previous call. - Total. Declare
var total = 0. It must be avar, because it changes as scores are added. - Loop over the scores.
for (s in scores)hands you one score per pass, in list order. Close its brace right away. - Add to the total. Inside the loop,
total += s. - Average. After the loop,
val average = total / scores.size. The loop has finished, sototalis the full sum. - Print three lines. Each one is the label, then the value:
Highest:,Lowest:andAverage:.
The solution in Kotlin
val scores = listOf(92, 78, 85, 67, 74, 88, 91, 58)
val highest = scores.max()
val lowest = scores.min()
var total = 0
for (s in scores) {
total += s
}
val average = total / scores.size
println("Highest: $highest")
println("Lowest: $lowest")
println("Average: $average")
Kotlin details worth knowing:
max()andmin()return anInt. In current Kotlin they return the element itself, not a nullable value. If you need a result that isnullfor an empty list,maxOrNull()andminOrNull()do that.listOfis read-only. It gives aList<Int>that you can read but not change: there is noaddon it. AMutableList, made withmutableListOf, can change.scores.sizeis a property. A list's size is written without parentheses,scores.size.+=on avar.total += sis shorthand fortotal = total + s. It works only becausetotalis avar.- The loop is a choice.
scores.sum()returns the same 633 in one call. The lesson writes the loop so that you practise the accumulator pattern, which you will need when there is no ready-made function.
Following the program
The running total grows by one score per pass: 92, then 170, 255, 322, 396, 484, 575 and finally 633. After the loop, average is 633 / 8. The mathematical value is 79.125, and the Int division keeps only the 79. Converting the total to Double first, total.toDouble() / scores.size, would give 79.125, but the lesson asks for the whole number.
Edge cases and common mistakes
- An empty list.
emptyList<Int>().max()throws aNoSuchElementException, and0 / list.sizethrows anArithmeticExceptionwith the message/ by zero. The lesson's data always has scores, so it doesn't guard against this. - One score. For
listOf(70)the highest, the lowest and the average are all 70. - Negative values. Starting a hand-written search for the biggest value at 0 is a trap: for the list
-3, -9it would report 0, which isn't in the list. That is one reason to prefermax(), which returns -3. - Truncation. The scores 1, 2 and 2 give an average of 1, not 2, because 5 divided by 3 is truncated.
valfor the total. Aval totalcan't be changed in the loop, and the compiler rejectstotal += s. The accumulator has to be avar.
Testing
| scores | Output |
|---|---|
| 92, 78, 85, 67, 74, 88, 91, 58 | Highest: 92, Lowest: 58, Average: 79 |
| 70 | Highest: 70, Lowest: 70, Average: 70 |
| 1, 2, 2 | Highest: 2, Lowest: 1, Average: 1 |
