{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

COS110Tutorial9-memo-10Oct2011

# COS110Tutorial9-memo-10Oct2011 - 1 COS110 Tutorial 9...

This preview shows pages 1–3. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 COS110 Tutorial 9 MEMO-MEMO-MEMO 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

{[ snackBarMessage ]}

### Page1 / 5

COS110Tutorial9-memo-10Oct2011 - 1 COS110 Tutorial 9...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online