Recursion programme not working

I wrote the following code to reverse a number using recursion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  #include<iostream>
int reverse(int x,int f)
{  int y;

  while(f!=0)
   {  y=f%10;
      x= (x*10) + y;


    reverse(x,f/10);

  }

return x;

}

int main()
{  int a;
std::cin>>a ;
std::cout<<"Value of a  ="<<a;
std::cout<<"\nreverse value of a  = "<<reverse(0,a);
return 0;

}



My code is not giving any value of reverse at all.I tried to check that whther it is entering in while condition by printing a value inside it and saw that it is in infinite loop.Can anyne please help me finding the mistake.
You don't change f so it won't become 0 and the loop will never end.
The problem is that you shouldn't have a while loop. The recursion replaces the loop. So your while should just be an if.

There are a couple of other problems, too. Here's a fixed-up version.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

long reverse(long f, long x = 0) {
    if (f == 0) return x;
    return reverse(f / 10, x * 10 + f % 10);
}

int main() {
    long a;
    while (std::cin >> a)
        std::cout << reverse(a) << "\n\n";
}

Or,

1
2
3
long reverse(long f, long x = 0) {
    return f ? reverse(f / 10, x * 10 + f % 10) : x;
}

Last edited on
Topic archived. No new replies allowed.