Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this recursion give following output?

I have an exercise with following code:

def rec_count(number):
    print(number)
    # Base case
    if number == 0:
        return 0
    rec_count(number - 1)  # A recursive call with a different argument
    print(number)


rec_count(5)

which gives this output:

5
4
3
2
1
0
1
2
3
4
5

I don’t understand why after reaching 0 function doesn’t go on with negative numbers, and gives numbers from 1 to 5 instead. Can someone explain?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance

>Solution :

Regarding negative numbers: when rec_count(0) is called, we encounter a return statement before reaching rec_count(0-1). As soon as a return statement is reached, execution of the function ends, so rec_count(-1) is never called.

Regarding increasing numbers: note that there is a print(number) statement after the recursive rec_count call.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading