Post

Created by @nathanedwards
 at November 1st 2023, 10:20:35 am.

Exam Question:

Consider the following recursive Python function that calculates the sum of all numbers from 1 to n:

def sum_numbers(n):
    if n == 1:
        return 1
    else:
        return n + sum_numbers(n-1)
  1. Explain what a base case is in the context of recursive functions.
  2. Identify the base case(s) in the sum_numbers function and explain why it is necessary.
  3. Determine the value returned by the sum_numbers function when n is 5. Show the step-by-step process.

Answer:

  1. In the context of recursive functions, a base case is a condition that determines when the recursive calls should stop and the function should return a specific value. It provides a termination condition for the recursive calls and prevents the function from entering an infinite loop.

  2. In the sum_numbers function, the base case is when n is equal to 1. This is because when n reaches 1, there are no more numbers to add, and the sum of numbers from 1 to 1 is simply 1. The base case is necessary to stop the recursion and ensure that the function returns a value.

  3. To determine the value returned by the sum_numbers function when n is 5, we can follow the step-by-step process:

    • Call sum_numbers(5)

      • n is not equal to 1, so continue to the else block.
      • Return 5 + sum_numbers(4)
    • Call sum_numbers(4)

      • n is not equal to 1, so continue to the else block.
      • Return 4 + sum_numbers(3)
    • Call sum_numbers(3)

      • n is not equal to 1, so continue to the else block.
      • Return 3 + sum_numbers(2)
    • Call sum_numbers(2)

      • n is not equal to 1, so continue to the else block.
      • Return 2 + sum_numbers(1)
    • Call sum_numbers(1)

      • n is equal to 1, so return 1

    Substituting the values in the previous calls:

    • sum_numbers(2) returns 2 + 1 = 3
    • sum_numbers(3) returns 3 + 3 = 6
    • sum_numbers(4) returns 4 + 6 = 10
    • sum_numbers(5) returns 5 + 10 = 15

    Therefore, when n is 5, the sum_numbers function returns 15.