CPSC 110 Spring 2012 Quiz 4
Answer Key

    Instructions: The first problem asks you to read a function and determine what it does. The secon problem asks you to write a function given a description.

  1. What value would function(4) return? Show your work.
    # Comment: A function with 1 parameter
    
    To function(N):
      Set global Var to 1
      While N > 0 do:
         Set Var to Var × N
         Set N to N - 1
      Return Var
    















  2. Define a function named countMs(aList, M) that counts the number of occurrences of M in the list aList. For example, if we call the function with the list [1,2,2,3,3,2,1,4,1,2] and 2, as in
        countMs( [1,2,2,3,3,2,1,4,1,2], 2)
    
    it will return 4 because there are four 2s in the list.



     

    Instructions: The next two problems ask you to define a function in Pseudocode or write a loop algorithm. Model your answers after the Pseudocode algorithms in the first 2 questions. Be careful about indentation.

  3. Suppose you have a variable named list that contains the following values: [1,2,3,4,5,6,7,8,9]. What would be the final value of Var as a result of the following algorithm?
    # Comment: What is the final value of Var
    
       Set global Var to 0
       For each item in list do:
       If remainder(item, 4) = 0
          Set global Var to Var + item * item
    















  4. Convert the loop algorithm in problem #3 (above) to an equivalent while loop.