Skip to content

Keep a Running Total

The Course
•
18 min study

A loop on its own repeats work, but it forgets everything between passes unless you give it somewhere to keep a result. That place is a variable declared before the loop. Declare a total before the loop. Each pass updates that same variable, and it is still in scope after the loop ends, so you can print it.

This pattern is called an accumulator, and it is one of the most common shapes in programming. Totals, counts, the largest value seen so far and the number of valid records are all accumulators. The recipe is always the same: start with a value that means "nothing yet", update it on each pass, and read it once the loop is done.

Predict and run

What is the total of 1, 2 and 3?

Predict, then run Go
package main

import (
	"fmt"
)

func main() {
	total := 0
	for n := 1; n <= 3; n++ {
		total += n
	}
	fmt.Println(total)
}
Check your prediction
Text
6

Move total := 0 inside the loop and run it. Read the error about total, restore the line and explain the error.

Why the declaration goes outside

Braces mark a block, and a variable lives only in the block where it is declared. Declared inside the loop body, total would be created fresh, set to 0, on every pass, and it would disappear when the pass ended. The fmt.Println(total) after the loop could not see it at all, which is why Go reports undefined: total. Declared before the loop, one variable is shared by every pass and is still there afterwards.

Watch the total grow

Printing inside the loop is a good way to check an accumulator while you build it. Each line below shows the value after that pass. Once you trust the logic, remove the extra output so only the final answer remains.

Trace each pass Go
package main

import (
	"fmt"
)

func main() {
	total := 0
	for day := 1; day <= 4; day++ {
		total += 15
		fmt.Printf("After day %d: %d min\n", day, total)
	}
	fmt.Println("Week so far:", total)
}
Text
After day 1: 15 min
After day 2: 30 min
After day 3: 45 min
After day 4: 60 min
Week so far: 60

Counting only some passes

An accumulator does not have to change on every pass. Put the update inside an if and it changes only when the condition holds. That turns a total into a count of matching items. You can keep several accumulators in the same loop, each with its own starting value and its own rule.

A total and a count together Go
package main

import (
	"fmt"
)

func main() {
	total := 0
	longDays := 0
	for day := 1; day <= 7; day++ {
		minutes := day * 10
		total += minutes
		if minutes >= 40 {
			longDays++
		}
	}
	fmt.Println("Total minutes:", total)
	fmt.Println("Days of 40 or more:", longDays)
}
Text
Total minutes: 280
Days of 40 or more: 4

minutes is declared inside the loop on purpose. It is only needed during one pass, so it is fine for it to be created fresh each time. total and longDays must survive between passes, so they live outside.

Choose the starting value with care

Start a total or a count at 0, because adding to zero changes nothing. Tracking the largest value is different: start it at the first real value, or at a value you know is smaller than any valid input. Starting a maximum at 0 works for minutes, which are never negative, but would silently fail for temperatures below zero.

From total to average

Once the loop has a total and a count, an average is one division away. Remember from Day 1 that dividing two int values drops the remainder. For a report in whole minutes that is usually fine; just make sure the count is not zero before you divide, or the program stops with a division by zero error.

Practice

Exercise

Your turn

For days 1 through 6, day n records n * 7 minutes. In one loop, add up the total and count the days under 20 minutes. After the loop, print the total, the count and the average per day in whole minutes. The output should be:

Text
Total: 147
Short days: 2
Average: 24
Your working space Go
package main

func main() {
	// Write your code here.
}
Hint 1: the idea

You need two accumulators, both declared before the loop. The total changes on every pass. The count changes only when an if says so.

Hint 2: a first step

Inside the loop, work out minutes := day * 7 and print it. Check that you get 7, 14, 21, 28, 35 and 42 before you add anything up.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func main() {
	total := 0
	shortDays := 0
	days := 6
	for day := 1; day <= days; day++ {
		minutes := day * 7
		total += minutes
		if minutes < 20 {
			shortDays++
		}
	}
	fmt.Println("Total:", total)
	fmt.Println("Short days:", shortDays)
	fmt.Println("Average:", total/days)
}
Text
Total: 147
Short days: 2
Average: 24

147 / 6 is 24.5, and int division keeps 24. Storing the number of days in days means the loop and the average can't disagree about how many days there were.

Was this article helpful?

Your response is saved on this device.