+ 1

A C++ Program - Looks Simple yet not simple enough to Understand. [Recursive function]

Someone please help me understand how this code working. I'm not sure how the hell does it prints from 5 to 1. Someone please help me out. Its just making me go mad even how simple this program looks yet its not simple enough to understand. Have a look at the code here :- https://code.sololearn.com/cXrExlFDK6Nh/?ref=app

4th Apr 2017, 6:43 AM
alex merceR
alex merceR - avatar
6 Answers
+ 5
bro that's your function, void recurse(int count) { if(count>5) return; recurse(count+1); cout<<"count = "<<count<<endl ; return; } let's understand it step by step; you call it for count=1 as it is <5 it will skip the if-part, then it call itself for count+1=2, now, until execution of recursion will not complete, it will not go to the cout part, so for count=2 it did the same call it for count=3, and then for 4,5 now when count=6, you get return from the function /* which is being called of count=6 */ still you are in function (for count=5 call), now here comes the cout part, now you comes to print count=5, then you will return from that function and get back to previous call ( for count=4) , then print 4, and then return from it, now you are in the call when count=3, and print 3 return ... did the same till (count=1)'s call will not return . now I think you got why its being print in reverse.
4th Apr 2017, 11:45 AM
Nikhil Dhama
Nikhil Dhama - avatar
+ 4
Basically, the function takes in a number. Then it checks, if the number is bigger than 5, it stops the function Else, it calls itself again, this time with (input value +1) and prints out a sentence afterwards.
4th Apr 2017, 6:53 AM
Wen Qin
Wen Qin - avatar
+ 4
your welcome
4th Apr 2017, 12:09 PM
Nikhil Dhama
Nikhil Dhama - avatar
+ 2
Why do you think that it never reaches the cout? The function checks if the count is greater than 5. If it is, it ends the recursion. Otherwise, it calls itself with an increased count, then outputs the current count. Since it outputs the count after it calls itself, the output will be in descending order.
4th Apr 2017, 6:51 AM
Luca Garrera
+ 1
Alright, but why it's coming in descending order exactly ? Can yu be more specific on this point please ?
4th Apr 2017, 7:36 AM
alex merceR
alex merceR - avatar
+ 1
Thankyou so much @Nikhil
4th Apr 2017, 12:07 PM
alex merceR
alex merceR - avatar