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.
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:
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.
Combine each piece of the data into the accumulator. The first program uses addition to add each value to the number sum. The second program uses concatenation to build up the string binary.
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:
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.