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)
sum_numbers
function and explain why it is necessary.sum_numbers
function when n
is 5. Show the step-by-step process.Answer:
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.
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.
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.5 + sum_numbers(4)
Call sum_numbers(4)
n
is not equal to 1, so continue to the else block.4 + sum_numbers(3)
Call sum_numbers(3)
n
is not equal to 1, so continue to the else block.3 + sum_numbers(2)
Call sum_numbers(2)
n
is not equal to 1, so continue to the else block.2 + sum_numbers(1)
Call sum_numbers(1)
n
is equal to 1, so return 1Substituting 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.