CPSC 110 Spring 2012 Quiz 4 (Redo)

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

  1. What value would function(4, 7) return? Show your work.
    # Comment: A function with 2 parameters
    
    To function(M, N):
      Set global Var to 0
      While M <= N do:
         Set Var to Var + M
         Set M to M + 1
      Return Var
    

    Interations M    N     Var    M <= N  Var + M
    ----------------------------------------------
    Initiallly  4    7      0     True     0 + 4 = 4
    1           5    7      4     True     4 + 5 = 9
    2           6    7      9     True     9 + 6 = 15
    3           7    7      15    True     15 + 7 = 22
    4           8    7      22    False    The answer is 22
    
    

  2. Define a function named sumOdds(aList) that will compute the sum of the odd numbers in aList. For example, if we call the function with the list [1,2,3,4,5] as in
        sumOdds( [1,2,3,4,5] )
    
    it will return 9 because 1 + 3 + 5 = 9.

    To sumOdds( aList ) :
       Set global Sum to 0
       For each Num in aList do:
          If remainder(Num, 2) = 1 then do:    // I.e. If Num/2 gives a remainder of 1
             Set global Sum to Sum + Num
       Return Sum
    

     

    Instructions: The next two problems ask you to read and write loop algorithms.

  3. Suppose you have a variable named list that contains the following values: [10,20,3,4,5,20,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 item > length(list) then do:
             Set Var to Var + item
    
    

    Interations Var  Item  length(list) item > length(list)  List = [10, 20, 3, 4, 5, 20, 7, 8, 9]
    ----------------------------------------------------------------------------------------------
    Initiallly  0    10     9            True, so add 0 + 10
    1           10   20     9            True, so add 10 + 20
    2           30   3      9            False
    3           30   4      9            False
    4           30   5      9            False
    5           30   20     9            True, so add 30 + 20
    6           50   7      9            False
    7           50   8      9            False
    8           50   9      9            False  The final value of Var is 50
    


  4. Convert the loop algorithm in problem #3 (above) to an equivalent while loop. Be careful about indentation.
    Set global Var to 0
    Set global Index to 1
    While Index <= length(list) do:
       Set Item to list item at Index
       If Item > length(list) then do:
             Set Var to Var + item
       Set Index to Index + 1