CPSC 110-08: Computing on Mobile Phones
Spring 2012

The Running Total Pattern
Solutions to Exercises

CS Principles

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

Exercises

From the homework:

  1. Write and test a function named computeSumListFives that returns sum of the numbers that are multiples of 5 in a given list.
    # Function to calculate the sum of numbers divisible 
    #   by five in aList
    # Argument: aList contains a list of integers
    
    To computeSumListFives(aList) :
       Set global Sum to 0
       For each number in aList do:
          If the number is divisible by 5 then do:
              Set Sum to Sum + number
       Return Sum
    
    SumAList

  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.
    # Function to count the number of 0s in a list
    # Argument: theList contains a list of integers
    
    To countZeroes(theList) :
       Set global count to 0
       For each num in theList do:
          If the num = 0 then do:
              Set count to count + 1
       Return Sum
    
    SumAList

  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.
    # Function to calculate the factorial of N
    # N! = N * (N-1) * (N-2) * ... * 2 * 1
    # Argument: N, a positive number
    
    To factorial(N) :
       Set global product to 1
       For each k in the range(1, N, 1) do:
          Set product to product × k
       Return product
    
    SumAList