Why does this recursive function work endlessly and not print numbers in reverse order?

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 runs in an endless loop. Why is this so? I can not get the desired conclusion. The desired result should be 5 4 3 2 1. Thank you in advance

+4
source share
6 answers

In this recursive call:

 reverse(no--); 

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

To fix it, change it to read

 reverse(no - 1); 

Note that there is no reason to reduce no , since in the current recursive call you will never read no again. You can simply pass the value no - 1 to the function. In fact, you might not want to use it at all -- in recursive calls, since it almost always indicates an error in the code.

Hope this helps!

+12
source

You are using the post-decrement operator on no . First, it gets the value no and uses this as the value of the expression, and then decreases no (still using the underestimated value as the value of the expression). You probably want to use --no or even just no - 1 . (The former will change no , while the latter will not, but it does not matter, since no not referenced after this point.)

+3
source

Edit:

 reverse(no--); 

in

 reverse(no-1); 

no-- returns the original value before the reduction occurred. So this line will always call reverse(5) . Consequently, an infinite loop.

0
source

n-- is an increment that first uses n as an argument to a function, and then decreases n.

So n-- matters

 reverse(n); n = n - 1; 

Do you want --n

0
source

You are using a post-decrement. First evaluates, then decreases the value.

Change this:

 reverse(no--); 

:

 return reverse(--no); 

- no - pre-decrement. Decrease โ€œnoโ€ first, then pass the value for the return stroke.

Note that I return the value of the result, you should always return int because of its declaration.

0
source

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 return a number every time you call reverse, and you do not reduce it before using it.

0
source

Source: https://habr.com/ru/post/1487989/


All Articles