Another recursive problem. I'm trying to write a function that reverses an int value recursively. I think I've got the algorithm right, but I can't get the base case right. So my program ends up printing 5 infinitely... Here's the code:

``````#include <iostream>
#include <cmath>
using namespace std;

void reverseDisplay(int value){
while (value != 0){
if (value < 0){
cout << "-" << abs(value % 10);
reverseDisplay(value / -10); }
else{
cout << value % 10;
reverseDisplay(value / 10); } } }

int main(){
reverseDisplay(54321);
reverseDisplay(-54321);
return 0; }``````
4
Contributors
7
Replies
8
Views
7 Years
Discussion Span
Last Post by WaltP

Why are you using a `while` statement in a recursive function? It is going to cause a major problem on the return rewind. Turn it into an `if` .

Also, if x is negative, is x/-10 negative or positive?

You need to place a `return;` (with no value) statement somewhere in your recursive function otherwise it will keep going on and on. Think about what your variable "value" will be when you run out of digits and use that as your base case.

Only if falling out of the function's bottom is not the place for returning.

Right, I would certainly agree. I was just looking at the if and the else branches both calling the recursive function, but you're 1 step ahead MrP.

Here is the corrected code.

``````void reverseDisplay(int value)
{
if (value != 0) // this is the correction.
{
if (value < 0){
cout << "-" << abs(value % 10);
reverseDisplay(value / -10);
}
else {
cout << value % 10;
reverseDisplay(value / 10);
}
}
}``````

Also you must include "stdlib.h" in your source

Regards,
Sarma

Do NOT correct code for others. They learn nothing.

Also you must include "stdlib.h" in your source

For what function?

Also, please don't just give the OP the corrected code, help them arrive at it.

Here is the corrected code.

Also you must include "stdlib.h" in your source