15.6. List Accumulation

We have already encountered the accumulator pattern - where we loop through a list of values and combine them all. This is a natural thing to do with our lists. Say I want to total the points that were earned by a student on the quizzes. I might use the following program:

The key steps are described with comments. We always need to start with some initial value as our “accumulation variable”, loop through the items, and combine each value with the accumulation variable.

If I wanted to multiple a group of numbers together, my accumulator variable would need to start with 1 (the multiplicative identity). At each step, I would multiply the current value from the list by my accumulated value to get the new accumulated value. This is shown in the animation below, using product as the accumulator variable.

Activity: CodeLens 15.6.2 (cspcollectionsintro_listaccumulation2)

We can “accumulate” other types of data as well. Say I have a series of words stored in a list. I can use the accumulator pattern to build up one string with all of the words. My accumulator variable will need to start with an appropriate empty value for a string, which is "".

Activity: CodeLens 15.6.4 (cspcollectionsintro_listaccumulation4)

The following program should calculate the average of some numbers by adding them all up before dividing by the number of values there are and printing out the answer. Put the blocks in the correct order and indentation. You will not need them all.

You have attempted of activities on this page