Skip to main content

Section 22.7 The Accumulator Pattern

We have seen the two programs 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 several values and build up an answer.
In the first program, we accumulate the different values that value holds into the variable sum:
sum = 0
count = 0
message = "Enter an integer. Enter 0 or less to stop."
value = input(message)
while int(value) > 0:
    sum = sum + int(value)
    count = count + 1
    value = input(message)

print("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:
number = 11
binary = ""

while number != 0:
    remainder = number % 2
    binary = str(remainder) + binary
    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!\text{.}\) (\(7!\) means the value you get by calculating \(7 \cdot 6 \cdot 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1\))
One critical ingredient 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:

Checkpoint 22.7.1.

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 side and put them in the correct order and indentation on the right.
You have attempted of activities on this page.