Reputation: 73
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
Upvotes: 4
Views: 298
Reputation: 154
You want to do
int reverse(int);
int main()
{
int no =5;
reverse(no);
}
int reverse(int no)
{
if(no == 0)
return 0;
else
printf("%d",no);
return reverse(--no);
}
So that you're returning a number every time you call reverse and you decrement no before you use it.
Upvotes: 0
Reputation: 4051
You are using post-decrement. First evaluates, then reduces value.
Change this:
reverse(no--);
to this:
return reverse(--no);
--no is pre-decrement. First decrease "no", then pass the value to reverse.
Note that I'm RETURNING the result value, you function always have to return an int, due to its declaration.
Upvotes: 0
Reputation: 34265
n--
is post increment which first use n as argument of the function and then decrement n.
So n--
essentially does is
reverse(n);
n = n - 1;
What you want is --n
Upvotes: 0
Reputation: 2534
Change:
reverse(no--);
to:
reverse(no-1);
no--
returns the original value before the decrement occurred. So this line will always call reverse(5)
. Hence, infinite loop.
Upvotes: 0
Reputation: 372764
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!
Upvotes: 12
Reputation: 129001
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.)
Upvotes: 3