This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 1 COS110 Tutorial 9 MEMOMEMOMEMO Date: 12 October 2011 Time: 50 minutes Marks: 35 Student Surname and Initials:____________________________________________ Student number:__________________ Employee number:___________________ Question 1 Fibonacci [8 marks] (Scope: Lecture 26, textbook section 19.4) The Fibonacci function is recursively defined as follows: fib(n) = fib(n – 1) + fib(n – 2) if n > 1 fib(n) = 0 if n = 0 fib(n) = 1 if n = 1 and has the following recursive computational solution: int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n – 1) + fib(n – 2); } a. Write the code for an iterative version of the fibonacci function Your code should use only one for statement or while statement, and one if statement. (6 marks) b. Under what circumstances should the solution based on iteration be preferred to the solution based on recursion? Motivate your answer. (2 marks) Solution to a: int fibonacci(int n) { int fibNminus1, fibNminus2, fib; if ( (n == 0) (n == 1) ) fib = n; (1 mark) 2 else { fibNminus2 = 0; fibNminus1 = 1; (1 mark) for (int i = 2; i <= n; i++) { fib = fibNminus1 + fibNminus2; (4 marks) fibNminus2 = fibNminus1; fibNminus1 = fib; } } return fib; } Solution to b: If the application using the fibinacci function must execute as fast as possible and additionally the values of n to be used are large, then the iterative solution should be preferred. (1 mark) Reason: For iteration, there is only one copy of the function one call to the function and one return from the function. This is not the case for recursion. (1 mark) Question 2 Towers of Hanoi [12 marks] (Scope: Lecture 26, textbook section 19.7) Study the code below and answer the questions that follow:...
View
Full Document
 Spring '11
 unsure
 Recursion, Hanoi, 50 Minutes, int start, terminating condition

Click to edit the document details