CPSC 110 Spring 2012 Quiz 4

    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
    

      N    Var          Var × N
     ----------------------------------
      4     1           4
      3     4           12
      2     12          24
      1     24          24
      0     24          -            Var = 24 = 4 × 3 × 2 × 1 = 4!
    

  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.
    To countMs (aList, M):
       Set global Count to 0
       For each item in aList do:
          If item = M do:
             Set Count to Count + 1
       Return Count
    

     

    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
    


    Var    Item         Remainder(Item, 4)    Var + Item * Item
    -----------------------------------------------------------
    0       1                1               
    0       2                2               
    0       3                3  
    0       4                0                0 + 4 × 4 = 16
    16      5                1               
    16      6                2   
    16      7                3
    16      8                0                16 + 8 × 8 = 80
    80      9                1
    


  4. Convert the loop algorithm in problem #3 (above) to an equivalent while loop.
    Set global Var to 0
    Set global Index to 1
    While Index ≤ length(list) do:
       Set Item to list element at Index
       If remainder(Item, 4) = 0
          Set global Var to Var + Item × Item
      Set global Index to Index + 1