Instructions: The first three problems ask you to read a Pseudocode algorithm. Trace through each of them by hand, keeping track of the variables, to determine the answer to the question.
Problem Solution # Comment: A function definition that takes 1 parameter To functionA(a): Return: a + 100 Trace: functionA(5) returns 5 + 100 = 105
Problem Solution # Comment: A function with 2 parameters To functionB(m,n): Set Var to m Set m to m + 1 While M <= N do: Set Var to Var + m Set m to m + 1 Return Var m n Var Return ------------------------------------ 3 5 3 4 7 5 12 6 12
Problem Solution # Comment: A mystery function To mystery(x, y): Set M to x If y < x then do: Set M to y Return Mx y M Return -------------------------------- 3 2 3 2 2 mystery(3,2) returns 2 3 3 3 3 mystery(3,3) returns 3
Instructions: The next three problems ask you to define a
function in Pseudocode. Model your answers after the Pseudocode
algorithms in the first 3 questions.
# A function that returns the sum of its 3 arguments. To sum3(a, b, c): Return a + b + c
Algorithm Trace # A function to compute the average of the numbers from 1 to N To average(N): Set global Sum to 0 Set global Index to 1 While Index <= N do: Set Sum to Sum + Index Set Index to Index + 1 Return Sum / NN Sum Index Return --------------------------------- 4 0 1 1 2 3 3 6 4 10 5 10/4 = 2.5
Algorithm Trace # A function to compute 2^n by repeated multiplication To powerOf2(n): Set global Product to 1 # Multiplication so initialize with 1 Set global Index to 1 While Index <= n do: Set Product to Product * 2 # Repeatedly multiply the product by 2 Set Index to Index + 1 Return Productn Product Index Return ------------------------------------- 4 1 1 2 2 4 3 8 4 16 5 16 = 2^4