#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.
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;
}