6.4. The Accumulator PatternΒΆ

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”.

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

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 runningTotal = 0 inside the for statement? Not sure? Try it and find out.

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

(sq_accum3)

Note

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

Check your understanding

        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.n = int(input('How many odd numbers would
you like to add together?'))
thesum = 0
oddnumber = 1
---
for counter in range(n):
---
   thesum = thesum + oddnumber
   oddnumber = oddnumber + 2
---
print(thesum)
Next Section - 6.5. Functions can Call Other Functions