CPSC 110-08: Computing on Mobile Phones
Spring 2012

The Running Total Pattern

CS Principles

This activity focuses on algorithms and abstraction and addresses the following learning objectives:

Introduction

This less focuses on an abstract loop pattern -- the running total pattern -- which can be used to solve a range of related problems.

You should first complete the following homework, where we learned:

Running Total Pattern

Recall this version of the running total pattern from the homework:

# Function to calculate the sum of a list of numbers
# Argument: list contains a list of integers

To SumAList(list) :
   Set global Sum to 0
   Set global Index to 1
   While Index <=length(list) do:
      Add to the Sum the selected item in list at index Index
      Add 1 to the Index
   Return Sum
SumAList

This version uses a while loop to traverse through a list. If we focus just on the problem of computing the sum (the green parts) and ignore the problem of traversing the list, then the key elements of the running total pattern are these:

  1. Initialize a variable to store the running total (Set global Sum to 0).
  2. For each item that should make up the running total, add it to the running total.

Because it makes it easier for us to ignore the problem of traversing a list, the for each loop version of this algorithm makes it easier to see the running total pattern:

# Function using a for-each loop to compute the sum of a list of numbers.
# The list is named aList
# The variable num is used to represent each number in the list

To computeListSum(aList) :
   Set global Sum to 0
   For each num in aList do:
      Set Sum to Sum + num
   Return Sum
SumAList

Running Total Variations

Key Points

Exercises
Solutions

Working in pairs, perform each of the following exercises. If you do not finish in class, do the exercises for homework. HINT: Some of the operations required for these exercises use built-in functions that can be found in the App Inventor Lists and Text menus.

  1. Write and test a function named computeSumListFives that returns sum of the numbers that are multiples of 5 in a given list.

  2. Write and test a function named countZeroes that will count the number of zeroes in a list. For example, if the list is [0 1 0 0 2 0 2], the function should return 4.

  3. The factorial of N is defined as N × N-1 × N-2 ... 2 × 1. Write a function to compute the factorial of N, where N is the argument. HINT: Try to see this as a running total problem.