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

Recommended Answers

All 7 Replies

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

Hope this was helpful.

Regards,
Sarma

commented: Do NOT correct code for others. They learn nothing. -2

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

Hope this was helpful.

No it wasn't. You don't get the grade, therefore you don't write their code. And we are trying to help him and you just wasted all the time we put in -- if your code actually works.

And suggesting stdlib.h is
1) not C++
2) not necessary

So all in all, a worthless post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.