educative.io

Educative

Recursion decrement example

Hello,

I am not understanding the second print command. Can you please explain step by step how the value of “number” is changing? Others have posted this question too but we have not gotten satisfactory response. Can you please explain the below pattern?

1
2
3
4
5

We are not incrementing the “number” explicitly and the value of number is not changed anywhere. Shouldn’t it just print “5” one time and exit?

Hello @Vandit,

The second print command will print the original number that was being passed to the function. To understand this, let us dry run the code for number = 2.

First print statement will print out 2 to the console. Next, the base case is checked and since the number is not equal to zero, the program flow will execute the recursive call rec_count(2 - 1). It should be noted here that the last print statement will not be executed until all the recursive calls have been returned.

After that 1 is printed onto the console and since number is still not equal to zero, the recursive call rec_count(1 - 1) will be executed.

Finally, 0 will be printed onto the console and now our number is equal to zero, and hence recursive calls will now start to return to the second print statement and 1 and 2 will be printed onto the console respectively.

Point to be noted here is that line 7 will not be executed until all the recursive calls from line 6 have been returned.

Hope this helps!

1 Like

How? did not understand. Now the number equals 0. until that I understand. when the recursive call returns to the second print statement, the value of number is 0?. how does it print 1 and then 2?

Hi. I’ve been sat here for the last hour trying to figure out that same thing but have finally figured it out by trying to draw out each step of the recursion and replacing “number” with the actual number at each stage:

What’s key here, and what took me a long time to figure out, is that line 7 of the original code (the second print statement) does not get executed until the base case (if number == 0) has been reached. However, that second print statement is essentially being “queued up” everytime “rec count” is called. Once “number” is 0, the recursion ends and every print statement that has been called on each step of the recursion is then executed, starting with the lowermost which is 1, then 2, then 3, then 4 and finally 5, hence why you get 5,4,3,2,1,0,1,2,3,4,5 as your output.

I hope that makes more sense!

1 Like

Thanks!! @Jossiqua