This activity focuses on algorithms and abstraction and addresses
the following learning objectives:
15: The student can develop an algorithm.
16: The student can express an algorithm in a language.
20: The student can use abstraction to manage complexity in a program.
Exercises
From the homework:
Modify the computeListSum function so that it computes the sum of only
the odd numbers in a list. Name your new function computeListSumOdds.
# Function to sum the odd numbers in a list
# Argument: aList1 contains a list of integers
To computeListSumOdds(aList1) :
Set global Sum to 0
For each num1 in aList1 do:
If the num1 is divisible by 2 then do:
Set Sum to Sum + num1
Return Sum
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
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
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