You are on page 1of 2

RECURSION EXERCISES

1. What is going to be the output of the following algorithm?


a. method foo(n)
if (n<=1) then
return 1
else
return foo(n-1) + foo(n-2)
end if
end method
output foo(5)
b. method foo(n,m)
if (n<=1) OR (m<=1) then
return 2
else
return foo(n-1,m) + foo(n,m-2)
end if
end method
output foo(5,4)
c. method foo(n,m)
output “value of n= ”, n, “value of m = ”, m
if (n<=1) OR (m<=1) then
return 2
else
return foo(n-1,m-n) + foo(n,m-2)
end if
end method
output foo(3,2)
d. method foo(X,Y)
if X<Y then
return foo(X+1,Y-2)
else if X=Y then
return 2*foo(X+2,Y-2)-3
else
return 2*X+3*Y
end if
end method
output “Output is”, foo(3,12)

2. What value does method a return when called with a value of 4?


method a(number)
if (number<=1)then
return 1
else
return number*a(number-1)
end if
end method
3. State three disadvantages of a recursive algorithm.
4. Describe why the use of recursion is memory intensive.
5. Create a recursive method in pseudocode addIntUpTo(n) for n>0 that will add all numbers from and
including n down to 1.
6. a. Create a fractal drawing algorithm in pseudocode and trace it for depths 1, 2 and 3.
b. Once you are satisfied with your pseudo code and tracing, attempt the code implementation in
Python.
7. Determine the pseudo code for the Fibonacci sequence, test it by tracing with 2 or 3 different outputs,
then code it in python.
8. Most illustrations of recursive functions address mathematical phenomena. As a non-numeric example,
consider the literary phrase “A rose is a rose is a rose is a rose.” that is based on a poem by Gertrude
Stein. The appeal of the phrase is largely due to its recursive aspect — so we should be able to use
recursion to program a generator function for it.
a. What part of the phrase is recursive? Which one is not?
b. What is the stopping condition? What should happen when it is reached?
c. Write a recursive function get_phrase(x = "rose", n = 3) that generates the phrase by
repeating the part "is a" x n times. Try writing a truly recursive function.
9. Write a function in python to solve the towers of Hanoi problem for n discs.

You might also like