Class XII Computer Science
Home Assignment – 3
Recursion
1. What do you mean by recursion?
2. Trace the program given below, if we pass 5 in nterms.
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
nterms = int(input("enter a number"))
if nterms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fib(i))
3. What is the output of the following piece of code?
def test(i,j):
if(i==0):
return j
else:
return test(i-1,i+j)
print(test(4,7))
4. Differentiate between iteration and recursion.
5. What is a base case and recursive case? What is their role in a recursive program?
6. When does infinite recursion occur?
7. State one advantage and one disadvantage of using recursion over iteration?
8. Fill in the line of code for calculating the factorial of a number.
def fact(num):
if num == 0:
return 1
else:
return _________
9. After filling in the line of above program, trace it ,if we pass num as 5.
10. What happens if the base condition isn’t defined in recursive programs?
11. What happens if recursive function reaches its depth of 1000 calls?
12. What is the output of the following piece of code?
def a(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return a(n-1)+a(n-2)
for i in range(0,4):
print(a(i),end=" ")
13. Determine the output of the following codes :
a) def area (s,a) : b) def express (x,n) :
return (s*s) if n==0 :
def area (b , h = 5) : return 1
return (0.5 *b * h) elif n%2==0 :
def main() : return express (x*x , n/2)
print(area(5,1)) else :
print(area(4,3)) return express x * (x , n-1)
print (area ( 6 , area(3,1))) express (2,5)
main()
c) def mystery(a,b) : d) def test (n) :
if a<=b : if n==0 :
m = (a+b)/2 return 0
mystery (a , m-1) if n==1 :
print(m) return 1
mystery (m+1 , b) if n==2 :
def (0,8) return 1
return 2 * test(n-2) * test(n-3)
for i in range (7) :
t = test (i)
print ( t , end = ‘@’ )
e) def sample (i , j) : f) def check (n) :
if i == 0 : if n<=1 :
return j return True
else : elif n%2 == 0 :
return sample(i-1 , i+j) return check (n/2)
print (sample (3,8) ) else :
return check (n/1)
check (8)
g) def func (n) : h) def recur (p) :
print (n , end = “ “) if p == 0 :
if n< 3 : print (“# #” )
return n else :
else : recur (p)
return func (n//2) – func(n//3) p = p-1