4.7. The Accumulator Pattern

In this section we will create a program that computes the square of a number. The program will use an algorithm with addition instead of multiplication. If you want to multiply two numbers together, the most basic approach is to think of it as repeating the process of adding one number to itself. The number of repetitions is where the second number comes into play. For example, if we wanted to multiply three and five, we could think about it as adding three to itself five times. Three plus three is six, plus three is nine, plus three is 12, and finally plus three is 15. Generalizing this, if we want to implement the idea of squaring a number, call it n, we would add n to itself n times.

Do this by hand first and try to isolate exactly what steps you take. You’ll find you need to keep some “running total” of the sum so far, either on a piece of paper, or in your head. Remembering things from one step to the next is precisely why we have variables in a program. This means that we will need some variable to remember the “running total”. It should be initialized with a value of zero. Then, we need to update the “running total” the correct number of times. For each repetition, we’ll want to update the running total by adding the number to it.

In words we could say it this way. To square the value of n, we will repeat the process of updating a running total n times. To update the running total, we take the old value of the “running total” and add n. That sum becomes the new value of the “running total”.

Here is the program in activecode:

In the program above, notice that the variable running_total starts out with a value of 0. Next, the iteration is performed to_square times. Inside the for loop, the update occurs. running_total is reassigned a new value which is the old value plus the value of running_total.

This pattern of iterating the updating of a variable is commonly referred to as the accumulator pattern. We refer to the variable as the accumulator. This pattern will come up over and over again. Remember that the key to making it work successfully is to be sure to initialize the variable before you start the iteration. Once inside the iteration, it is required that you update the accumulator.

Note

What would happen if we put the assignment running_total = 0 inside the for statement? Not sure? Try it and find out.

Here is the same program in codelens. Step through the function and watch the “running total” accumulate the result.

(sq_accum3)

The General Accumulator Pattern

initialize the accumulator variable
repeat:
    modify the accumulator variable

when the loop terminates the accumulator has the correct value

Check your understanding

    func-4-1: Consider the following code:

    to_square: int
    running_total: int
    
    to_square = 10
    running_total = 0
    for i in range(0, to_square, 1):
        running_total = running_total + to_square
    print("The result of " +  str(to_square) + " squared is " + str(running_total))
    

    What happens if you put the initialization of running_total (the line running_total = 0) inside the for loop as the first instruction in the loop?

  • The program will compute to_square instead of to_square * to_square
  • The variable running_total will be reset to 0 each time through the loop. However because this assignment happens as the first instruction, the next instruction in the loop will set it back to to_square. When the loop finishes, it will have the value to_square.
  • The program will produce an error
  • Assignment statements are perfectly legal inside loops and will not cause an error.
  • The program will work as expected and compute to_square * to_square
  • By putting the statement that sets running_total to 0 inside the loop, that statement gets executed every time through the loop, instead of once before the loop begins. The result is that running_total is 'cleared' (reset to 0) each time through the loop.
  • The program will compute 0 instead of to_square * to_square
  • The line running_total = 0 is the first line in the for loop, but immediately after this line, the line running_total = running_total + to_square will execute, giving running_total a non-zero value (assuming to_square is non-zero).
        func-4-2: Rearrange the code statements so that the program will add up the first n odd numbers where n is provided by the user.the_sum: int
odd_number: int

print("How many odd numbers would you like to add together?")
n = int(input())
the_sum = 0
odd_number = 1
---
for i in range(0, n, 1):
---
   the_sum = the_sum + odd_number
   odd_number = odd_number + 2
---
print(the_sum)
        
You have attempted of activities on this page
Next Section - 4.8. A Few More turtle Methods and Observations