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
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!
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With