Recursion (concept & tracing)

Computer Science · Programming fundamentals

Question 1 of 10

0

    What does this program print? def f(n): if n == 0: return 0 return n + f(n - 1) print(f(3))

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Recursion (concept & tracing) explained

    Recursion is when a function solves a problem by calling itself on a smaller version of the same problem. Every recursive function needs a base case, a condition where it stops and returns an answer directly. Without one, the calls would never end. The recursive case is the part that reduces the problem and makes the call.

    To trace a recursive function, write down each call as it starts, then fill in the returned values from the innermost call outwards. Each call waits until the call it made has returned, so the calls stack up on top of one another in memory.

    A common mistake is a recursive call that never gets closer to the base case, such as calling fact(x + 1) instead of fact(x - 1). The function then runs until the computer runs out of stack memory and reports a stack overflow error.

    Worked example

    Trace fact(4) using this function:

    def fact(x):
        if x <= 1:
            return 1
        return x * fact(x - 1)
    
    1. fact(4) needs fact(3), so it waits. Likewise fact(3) waits for fact(2), and fact(2) waits for fact(1). That is 4 calls in total.
    2. fact(1) meets the base case and returns 1.
    3. Working back: fact(2) returns 2×1=22 \times 1 = 2, fact(3) returns 3×2=63 \times 2 = 6, and fact(4) returns 4×6=244 \times 6 = 24.

    Check: 4×3×2×1=244 \times 3 \times 2 \times 1 = 24, which is 4 factorial.

    Key facts

    The practice questions give a short Python function f(n) and ask what it prints, or how many times f is called. Three patterns come up.

    • One call each time: the answer builds up from the base case, for example f(n)=n+f(n−1)f(n) = n + f(n-1) or 2×f(n−1)2 \times f(n-1).
    • Halving: calls use n // 2 (integer division). The number of calls to reach 1 is ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1, counting the first call.
    • Two calls each time: the number of calls grows very fast. For f(n)=f(n−1)+f(n−1)f(n) = f(n-1) + f(n-1) with base case n = 0, the calls total 2n+1−12^{n+1} - 1.

    When you count calls, count every call, including the first and the base-case calls.

    Worked example 2

    What does this print?

    def f(n):
        if n <= 1:
            return 1
        return f(n // 2) + n % 2
    
    print(f(45))
    

    Work down until the base case, then back up.

    1. f(45) = f(22) + 1, because 45 mod 2=145 \bmod 2 = 1.
    2. f(22) = f(11) + 0.
    3. f(11) = f(5) + 1.
    4. f(5) = f(2) + 1.
    5. f(2) = f(1) + 0.
    6. f(1) = 1 (base case).

    Back up: f(2) = 1, f(5) = 2, f(11) = 3, f(22) = 3, f(45) = 4. The program prints 4. In binary, 45=101101245 = 101101_2, which has four 1s, so this function counts the 1 bits.

    Worked example 3

    How many times is f called while evaluating f(6)?

    def f(n):
        if n < 2:
            return n
        return f(n - 1) + f(n - 2)
    

    Let C(n)C(n) be the number of calls. For n = 0 or 1 there is one call. Otherwise it is the call itself plus the calls it makes: C(n)=1+C(n−1)+C(n−2)C(n) = 1 + C(n-1) + C(n-2).

    1. C(0)=1C(0) = 1 and C(1)=1C(1) = 1.
    2. C(2)=1+1+1=3C(2) = 1 + 1 + 1 = 3.
    3. C(3)=1+3+1=5C(3) = 1 + 3 + 1 = 5.
    4. C(4)=1+5+3=9C(4) = 1 + 5 + 3 = 9.
    5. C(5)=1+9+5=15C(5) = 1 + 9 + 5 = 15.
    6. C(6)=1+15+9=25C(6) = 1 + 15 + 9 = 25.

    So f is called 25 times. The value returned is only 8, so the number of calls is far larger than the answer.

    Worked example 4

    What does f(7) return?

    def f(n):
        if n < 3:
            return n
        return f(n - 1) + 2 * f(n - 3)
    

    The base cases give f(0) = 0, f(1) = 1 and f(2) = 2. Build upward, because each value only needs earlier ones.

    1. f(3)=f(2)+2×f(0)=2+0=2f(3) = f(2) + 2 \times f(0) = 2 + 0 = 2.
    2. f(4)=f(3)+2×f(1)=2+2=4f(4) = f(3) + 2 \times f(1) = 2 + 2 = 4.
    3. f(5)=f(4)+2×f(2)=4+4=8f(5) = f(4) + 2 \times f(2) = 4 + 4 = 8.
    4. f(6)=f(5)+2×f(3)=8+4=12f(6) = f(5) + 2 \times f(3) = 8 + 4 = 12.
    5. f(7)=f(6)+2×f(4)=12+8=20f(7) = f(6) + 2 \times f(4) = 12 + 8 = 20.

    The answer is 20.

    Common mistakes

    • Working from the top and guessing the result. Find the base case, then work back.
    • Missing a base case. Here n = 0, 1 and 2 all return n.
    • Using ordinary division for n // 2. 45 // 2 is 22, not 22.5.
    • Forgetting the first call when counting calls.
    • Treating a function that calls itself twice as if it called itself once.

    Exam tips

    • Write each call on its own line as "f(k) = ..." and fill in values when the base case returns.
    • For "how many calls", draw the call tree or use a table of C(n)C(n) values.
    • Check halving calls: for 100, the values are 100, 50, 25, 12, 6, 3, 1, which is 7 calls.
    • A missing or unreachable base case gives a stack overflow, so mention it when asked what goes wrong.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this program print? def f(n): if n == 0: return 0 return n + f(n - 1)

      print(f(29))

    • Medium

      What does this program print? def f(n): if n < 3: return n return f(n - 1) + 2 * f(n - 3)

      print(f(8))

    • Hard

      def f(n): if n <= 1: return 0 return 1 + f(n // 2)

      How many times is f called in total while evaluating f(215), counting the first call?