Start learning free

LESSON 206 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Report Card V6 in Go: Highest, Lowest and Average of a Slice

Practice Read the full explanation

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

You start with:

scores := []int{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 (fmt.Println("Highest: " + strconv.Itoa(highest))).

Iterate over the slice once, tracking max and min manually, and accumulate the sum.

scores := []int{92, 78, 85, 67, 74, 88, 91, 58}

highest := scores[0]
lowest := scores[0]
total := 0
for _, s := range scores {
    if s > highest {
        highest = s
    }
    if s < lowest {
        lowest = s
    }
    total += s
}
average := total / len(scores)

fmt.Println("Highest: " + strconv.Itoa(highest))
fmt.Println("Lowest: " + strconv.Itoa(lowest))
fmt.Println("Average: " + strconv.Itoa(average))

STEP 1 OF 11
    Ctrl + Enter to check

    GO · PROJECTS: EVERYDAY PROGRAMS

    Report Card V6 in Go, explained

    Problem overview

    The last version of Report Card summarises a whole class. Given a slice of scores, the program prints the highest score, the lowest score and the average, rounded down:

    scores := []int{92, 78, 85, 67, 74, 88, 91, 58}
    

    The scores add up to 633 and there are 8 of them, so the average is 633 / 8 = 79.125, which becomes 79 with integer division. The output is:

    Highest: 92
    Lowest: 58
    Average: 79
    

    Approach: one pass, three running values

    Go has no built-in function that returns the largest value of a slice, and none is needed. A single loop can keep all three answers up to date as it goes:

    • highest, the largest score seen so far;
    • lowest, the smallest score seen so far;
    • total, the sum of all scores seen so far.

    The two extremes start at the first score, scores[0], which is by definition both the largest and the smallest of the one score seen so far. Starting them at fixed numbers such as 0 or 100 would break for scores outside that guess. After the loop, average is total / len(scores).

    The loop looks at every score once, so the work grows in step with the length of the slice.

    This table shows the three variables at the end of each pass over the starting scores:

    Score shighestlowesttotal
    92929292
    789278170
    859278255
    679267322
    749267396
    889267484
    919267575
    589258633

    The first pass compares 92 with itself, so nothing changes except total. The highest never moves again, because 92 is the first score and the largest. The lowest drops at 78, at 67 and finally at 58 in the last pass.

    Step by step

    1. Create highest as scores[0].
    2. Create lowest as scores[0] too.
    3. Create total as 0. A running sum begins at zero, before any score is counted.
    4. Loop over the scores with for _, s := range scores. The range gives an index and a value for each element, and the _ discards the index. Write the closing brace right away.
    5. Update the maximum. If s is greater than highest, assign it to highest.
    6. Update the minimum. If s is less than lowest, assign it to lowest. This is a separate if, not an else, because a score can be tested against both.
    7. Add to the total, after both checks and outside the ifs. Every score counts toward the sum, not just a new highest or lowest.
    8. Compute the average after the loop: total / len(scores). Both operands are int, so the fraction is dropped.
    9. Print three lines, each with a label and a number converted by strconv.Itoa.

    The solution in Go

    scores := []int{92, 78, 85, 67, 74, 88, 91, 58}
    
    highest := scores[0]
    lowest := scores[0]
    total := 0
    for _, s := range scores {
        if s > highest {
            highest = s
        }
        if s < lowest {
            lowest = s
        }
        total += s
    }
    average := total / len(scores)
    
    fmt.Println("Highest: " + strconv.Itoa(highest))
    fmt.Println("Lowest: " + strconv.Itoa(lowest))
    fmt.Println("Average: " + strconv.Itoa(average))
    

    The code uses the fmt and strconv packages. The Go details to know:

    • range gives the value as a copy. s is a copy of each element, which is fine here because the loop only reads it.
    • The blank identifier. Go refuses unused variables. If you wrote for i, s := range scores and never used i, the code wouldn't compile. _ is the way to say that you ignore the index.
    • := infers int. scores[0] is an int, so highest and lowest are int. total := 0 is an int too, since an integer literal defaults to int.
    • += adds in place. total += s means total = total + s.
    • len is an int. That is why total / len(scores) compiles with no conversion: both sides have the same type. Dividing by a float64 would need a conversion first.

    Complexity

    Time is O(n): the loop makes one pass over the n scores and does a constant amount of work for each. Space is O(1), since the program keeps only highest, lowest, total and average.

    Edge cases and common mistakes

    • An empty slice. scores[0] panics with index out of range [0] with length 0. The average would also divide by zero, which panics for integers in Go. The lesson's data is never empty.
    • One score. The loop compares the score with itself, nothing changes, and the three lines show that score three times. For {70} the output is 70, 70 and 70.
    • Starting highest at 0. It works for positive scores but fails for all-negative data. For {-10, -20, -5}, a highest that starts at 0 stays 0, which is not in the data. Starting at scores[0] gives the correct -5.
    • Truncation. The average of 99 and 100 is 99.5 and prints as 99. For negative totals Go truncates toward zero: the average of -10, -20 and -5 prints as -11, although the exact value is -11.67.
    • Counting only the extremes. If total += s sits inside one of the if blocks, the sum is wrong, and so is the average.
    • Dividing by a hard-coded 8. Use len(scores), so the program keeps working when the slice changes.

    Testing

    • The starting scores print Highest: 92, Lowest: 58 and Average: 79.
    • {70} prints 70, 70, 70.
    • {80, 80, 80} prints 80, 80, 80.
    • {99, 100} prints highest 100, lowest 99 and average 99.
    • {-10, -20, -5} prints highest -5, lowest -20 and average -11.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free