Tracing recursive functions: Class 12 practice
A recursive function calls itself on a smaller input until it reaches a base case. Read the method, follow the three worked examples, then try the six questions.
What you should know first
- Functions
The idea behind tracing recursive functions
A recursive function calls itself on a smaller input until it reaches a base case. Trace each call, then combine the returned values on the way back.
Step-by-step method
- Find the base case.
- Write the chain of calls down to the base case.
- Multiply/add results while returning.
Worked example 1 (Basic)
def f(n): return 1 if n <= 1 else n * f(n - 1). What is f(4) and how many calls are made?
- f(4) = 4 × f(3) … f(1) = 1
- = 24; calls: 4
- Answer: 24, 4 calls
Worked example 2 (Standard)
def s(n): return 0 if n == 0 else n + s(n - 1). What is s(8)?
- s(8) = 8 + … + 1 + 0
- Answer: 36
Worked example 3 (Challenge)
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2). What is fib(8), and how many calls does it make in total?
- fib(8) = 21
- Total calls = 67
- Answer: 21, 67 calls
Common mistakes and misconceptions
- Missing the base case value
- Counting the number of calls wrong
Practice questions
- (Basic) def f(n): return 1 if n <= 1 else n * f(n - 1). What is f(7) and how many calls are made?
- (Basic) def f(n): return 1 if n <= 1 else n * f(n - 1). What is f(3) and how many calls are made?
- (Standard) def s(n): return 0 if n == 0 else n + s(n - 1). What is s(7)?
- (Standard) def s(n): return 0 if n == 0 else n + s(n - 1). What is s(6)?
- (Challenge) def fib(n): return n if n < 2 else fib(n-1) + fib(n-2). What is fib(6), and how many calls does it make in total?
- (Challenge) def fib(n): return n if n < 2 else fib(n-1) + fib(n-2). What is fib(4), and how many calls does it make in total?
Answer key with full working
- Q1: f(7) = 7 × f(6) … f(1) = 1 → = 5040; calls: 7 → Answer: 5040, 7 calls
- Q2: f(3) = 3 × f(2) … f(1) = 1 → = 6; calls: 3 → Answer: 6, 3 calls
- Q3: s(7) = 7 + … + 1 + 0 → Answer: 28
- Q4: s(6) = 6 + … + 1 + 0 → Answer: 21
- Q5: fib(6) = 8 → Total calls = 25 → Answer: 8, 25 calls
- Q6: fib(4) = 3 → Total calls = 9 → Answer: 3, 9 calls
Syllabus note
This skill is listed under "Functions" for Class 12 in the NCERT/CBSE books. ICSE, IGCSE, IB and state boards may teach it in a different chapter or year.
Answers on this page are generated and automatically re-checked by a second, independent calculation. They have not been reviewed by a teacher — if you spot a problem, tell us on WhatsApp.
Related practice and notes
Frequently asked questions
Which chapter is tracing recursive functions in?
"Functions", Class 12 Computer Science (NCERT/CBSE). Other boards may place it differently.
How were the answers checked?
Answers on this page are generated and automatically re-checked by a second, independent calculation. They have not been reviewed by a teacher — if you spot a problem, tell us on WhatsApp.