Accumulate totals in a loop
Accumulate totals in a loop
An accumulator is a variable that stores a running result across iterations. Initialize it before the loop, update it within the loop, and read the final value afterward. For a sum the usual starting value is zero; for a product it is one.
package main
import "fmt"
func main() { total := 0 for i := 1; i <= 4; i++ { total += i } fmt.Println(total)}The running totals are 1, 3, 6 and 10. Declaring total inside the body would reset it each iteration and make it inaccessible afterward. Use += to add to the existing value rather than replacing it with i.
Count only matching values
package main
import "fmt"
func main() { count := 0 for i := 1; i <= 10; i++ { if i%3 == 0 { count++ } } fmt.Println(count)}The counter increases only for 3, 6 and 9. A count and a sum are different: adding i here would give 18, not 3. For large inputs, choose a numeric type that fits the expected total; integer overflow can change the result.
Try it locally
Compute the product of integers 1 through 5 with a loop. Initialize the accumulator correctly and print only the final result: 120.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loops 05: Accumulate totals in a loop
Check the lesson objective before moving on.
What is the correct initial value for a product accumulator?
Why declare total outside the loop?