Damian
Damian

Reputation: 13

recursive function does not work as expected

Could someone explain the code? I just can not understand why this code gives output like this:

1
3
6
10
15
21

I expected the code to give something like this:

1
3
5
7
9
11

What am I missing here?

def tri_recursion(k):
    if(k > 0):
        result = k + tri_recursion(k-1)
        print(result)
    else:
        result = 0
    return result

tri_recursion(6)

Upvotes: 0

Views: 53

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177471

For your recursive function, the termination condition is k=0.

It's clear that if k=0, tri_recursion(0) = 0.

If k=1, tri_recursion(1) = 1 + tri_recursion(0), which from above, is 1 + 0 or 1.
If k=2, tri_recursion(2) = 2 + tri_recursion(1), which from above, is 2 + 1 or 3.
If k=3, tri_recursion(3) = 3 + tri_recursion(2), which from above, is 3 + 3 or 6.
If k=4, tri_recursion(4) = 5 + tri_recursion(3), which from above, is 4 + 6 or 10.
If k=5, tri_recursion(5) = 4 + tri_recursion(4), which from above, is 5 + 10 or 15.
If k=6, tri_recursion(6) = 6 + tri_recursion(5), which from above, is 6 + 15 or 21.

See the pattern?

Upvotes: 2

bumblebee
bumblebee

Reputation: 1841

Your code is calculating the sum of numbers up to n where n is 6 in the above case. The print statement prints the intermediate results. Hence the output 1 3 6 10 15 21.

1 - The sum of numbers from 0 to 1

3 - The sum of numbers from 0 to 2

6 - The sum of numbers from 0 to 3

10 - The sum of numbers from 0 to 4

15 - The sum of numbers from 0 to 5

21 - The sum of numbers from 0 to 6

Upvotes: 2

Related Questions