Skip to main content

Section 8.4 Accumulating

A common task we need to do as part of a loop is to accumulate some valueβ€”to keep a running total of something. For example, we might want to add up all the numbers from 1 to 5. We could do that by creating a variable to hold the total, and then adding each number to the total as we go:
Listing 8.4.1.
This successfully adds up the numbers that 1-5 and gets 15. Key parts of the recipe:
  • The accumulator variable total is declared before the loop starts. If we put total inside the loop, it would be recreated with each iteration and never grow. (It would also be unavailable on line 11 once we left the loop.)
  • Where we change the accumulator, the variable we are adding, i has the correct value (1, then 2, then 3,...)
If we change the order of the statements in The loop body we will violate this second rule and get the wrong answer:
Listing 8.4.2.
Now, because we are Updating the loop counter first, by the time we change the accumulator we are using the wrong value. We could fix that by changing the loop itself to count from zero up to but not including five, but It is easier to just have ++i be the last statement.

Insight 8.4.1.

The structure for loops that generally keeps things as simple as possible is:
DO TEST ON CURRENT VALUE
    DO WORK WITH CURRENT VALUE
    GO TO THE NEXT VALUE (UPDATE LOOP CONTROL VARIABLE)
By updating the loop control variable at the end of the loop, we ensure that after changing the value, the next thing that happens is testing to see if we want to continue with the loop. If so, we use that value, then calculate the next one.

Checkpoint 8.4.1.

The program below should find the sum of the first 10 natural numbers, but the code is mixed up and contains extra blocks. Put the necessary blocks in the correct order.
You have attempted of activities on this page.