954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Recursion

Why Does this code Leads to Infinite Loop?????

#include<stdio.h>
#include<conio.h>
int reverse(int);
void main()
{
 int no=5;
 reverse(no);
 getch();
}

int reverse(int no)
{
 if(no==0)
 {
  return 0;
 }
 else
 {
  printf("%d",no);
 }
 reverse(no--);
}
ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

I would say that once 5 is decremented to 0, it stays as 0 as all you have is 'return 0' doing nothing else, and you have no system exit at that point.

StephNicolaou
Posting Whiz in Training
204 posts since Nov 2007
Reputation Points: 77
Solved Threads: 18
 

Steph Nicolaou ..its never entering the "if" part, you can check that. and if it has entered then the program would have ended after returning 0..
and the best part of this program is, 5 is never getting Decremented . Might be post Decrement doesn't work with recursion as it doesn't work with return.

ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

It has to do with the way the call reverse(no--) is being implemented. The post decrement operator allows for the variable to be used in it's contextbefore it is decremented. So, in your situation it is using the original value of no for the recursive call and decrementing itafter that (which never occurs). Change that to reverse(--no) or reverse(no - 1) and you will get the behavior you are after.

L7Sqr
Practically a Master Poster
657 posts since Feb 2011
Reputation Points: 201
Solved Threads: 124
 

Thanks L7Sqr :).......... Thread Solved.............

ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You