Skip to content

Question 22

Given that n is a positive integer, what does the following function return?

1
2
3
4
def rec(n):
    if n == 1:
        return n
    return n + rec(n-1)
Hint

Take any arbitrary value of n, where n is a positive integer (i.e., 1, 2, 3, ...). By tracing, what would the working be?

Solution

This function rec() is a recursive function, which returns the input value n if n == 1, and a sum of n and a recursive call to the same function with input n-1 otherwise.

Say n = 5. The working of the function will be like such:

rec(5)
= 5 + rec(4)
= 5 + [ 4 + rec(3) ]
= 5 + 4 + [ 3 + rec(2) ]
= 5 + 4 + 3 + [ 2 + rec(1) ]
= 5 + 4 + 3 + 2 + 1

Plug in any other value of n and you will notice a similar pattern - rec() produces the sum of integers from 1 to n (inclusive).

Answer

The sum of integers from 1 to n (inclusive)