10.7. The Accumulator PatternΒΆ

We have seen the two program below before. They do very different jobs - one turns a decimal number into a binary one, the other lets the user enter numbers and then prints out their average. However, there is a common pattern in these programs - the Accumulator Pattern. The accumulator pattern is a common recipe for using a loop to combine a number of values and build up an answer.

In the first program, we accumulate the different values that value holds into the variable sum:

 1sum = 0
 2count = 0
 3message = "Enter an integer. Enter 0 or less to stop."
 4value = input(message)
 5while int(value) > 0:
 6    sum = sum + int(value)
 7    count = count + 1
 8    value = input(message)
10print("The sum is: " + str(sum) + " the average is: " + str(sum / count))

In the second program, we accumulate the different values that remainder holds into the variable binary:

1number = 11
2binary = ""
4while number != 0:
5    remainder = number % 2
6    binary = str(remainder) + binary
7    number = number // 2

Here are the five steps in this pattern:

  1. Set the accumulator variable to its initial value. This is the value we want if there is no data to be processed. For the first loop, the sum is set to 0. For the second loop, binary is set to the empty string "". This happens before the loop.

  2. Use a loop to iterate through all the data. There should be a variable that on each value in the data we are trying to accumulate.

  3. Combine each piece of the data into the accumulator. The first program uses + to add each value to the number sum. The second program uses + to build up the string binary.

  4. Once the loop is done, do something with the result.

What is the sum of all the numbers between 1 and 100? We can answer that easily using our pattern.

Step 3 does not have to use + to build up our answer. We could use * in the accumulator pattern to build up the value of \(7!\). (\(7!\) means the value you get by calculating \(7 \cdot 6 \cdot 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1\))

One ingredient that is critical is that we do step 1 before the loop starts. If we try to initialize the accumulator in the loop we will just keep resetting it. Watch this failed attempt to add up the numbers from 1 to 5 run line by line to see why:

Activity: CodeLens 10.7.3 (csprepeatnumbers_accumpattern3)

The following is the correct code for printing the sum of all the odd numbers from 1 to 29 using the accumulator pattern, but it is mixed up. Drag the blocks from the left and put them in the correct order and indentation on the right.

You have attempted of activities on this page