Home > Software engineering >  Recursive functions: can someone explain how this code printed 1 to 5?
Recursive functions: can someone explain how this code printed 1 to 5?

Time:12-18

def recursion_1(n):
    if n == 0:
        return
    recursion_1 (n-1)
    print(n)

I don't understand how this code printed 1 to 5 the same way a for loop would have printed a list of range from 1 to 5. Passing 5 as the argument here.

CodePudding user response:

The best way to understand it is probably to imagine how it would look if you replaced the function calls with its definition.

So recursion_1(5) becomes :

if 5 == 0:
    return
recursion_1 (4)
print(5)

Which in turn is equivalent to :

if 5 == 0:
    return
if 4 == 0:
    return
recursion_1 (4)
print(4)
print(5)

Et cetera until :

if 5 == 0:
    return
if 4 == 0:
    return
if 3 == 0:
    return
if 2 == 0:
    return
if 1 == 0:
    return
recursion_1 (0)
print(1)
print(2)
print(3)
print(4)
print(5)

Then recursion_1(0) will return because the condition is met (0 == 0 is true) and each precedent call will return after printing its number.

  • Related