# Reversing a set of numbers using recursion

• 02-14-2002
Shikimo
Reversing a set of numbers using recursion
I have an algorithm here that'll let me compute the reverse of a given set of integers without using strings or arrays (which is the goal). However, I've no idea how to work recursion into this function. It's driving me up a wall.

-----------------------------------------

#include <iostream.h>
#include <stdlib.h>
#include <limits.h>

void ReverseDigits(int number);

int main()
{
int number;

do
{
cout << "Enter a number between 0 and "
<< INT_MAX << ": ";
cin >> number;
cin.ignore(999, '\n');
while (number < 0)
{
cerr << "Input error: value entered is not between 0 and "
<< INT_MAX << endl;

cout << "Enter a number between 0 and "
<< INT_MAX << ": ";
cin >> number;
cin.ignore(999, '\n');
}

cout << "The number written in the usual way: " << number << endl;
cout << "The number with its digits reversed: ";
ReverseDigits(number);
cout << endl;

cout << "Do another customer? (n = no, any other = yes) ";
cin.ignore(999, '\n');
}

cout << "Press Enter or Return when ready..." << endl;
cin.get();
return EXIT_SUCCESS;
}

// write definition for ReverseDigits

// Here's where I get lost. How do I make this recursive?

void ReverseDigits(int number)
{
int result = 0;

while ( value % 10 )
{
result *= 10;
result += value % 10;
value /= 10;
}
}
• 02-14-2002
Unregistered
recursion occurs when the function calls itself until a predefined endpoint is reached (if not end point then you have frozen the computer, and that ain't good).

So what's the endpoint? If number is < 10 I suppose.

here's a basic recursive function outline

returnType functionName(parameterList)
{
conditional statement to check for endpoint;
if endpoint achieved do something (or nothing too sometimes);

otherwise manipulate things if you need to here;
call the funciton again; //re-curse it!
do something else here if you want
}
• 02-14-2002
Shikimo