Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this recursive function loop infinitely rather than printing numbers in reverse?

Tags:

c

recursion

int reverse(int);
void main()
{
     int no =5;
     reverse(no);
}

int reverse(int no)
{

 if(no == 0)
      return 0;
else 
 printf("%d",no);

reverse(no--);
}

This program goes in infinite loop.Why is that so? I am not able to get the desired ouput. Desired output should be 5 4 3 2 1.Thank you in advance

like image 899
user1208523 Avatar asked Dec 07 '22 07:12

user1208523


2 Answers

In this recursive call:

reverse(no--);

You are passing the value of no--. Since this uses the postfix -- operator, this means "decrement no, then pass the original value of no into the recursive call to reverse." This causes infinite recursion, since you are constantly making a recursive call with reverse set to the same value.

To fix this, change this to read

reverse(no - 1);

Notice that there's no reason to decrement no here, since within the current recursive call you will never read no again. You can just pass the value of no - 1 into the function. In fact, you might want to in general avoid using -- in recursive calls, since it almost always indicates an error in the code.

Hope this helps!

like image 114
templatetypedef Avatar answered Jan 01 '23 20:01

templatetypedef


You're using the post-decrement operator on no. That first gets the value of no and uses that as the value of the expression and then decrements no (still using the undecremented value as the value of the expression). You probably want to use --no or even just no - 1. (The former will modify no, whereas the latter will not, but it does not matter because no is not referenced after that point.)

like image 42
icktoofay Avatar answered Jan 01 '23 21:01

icktoofay