# Thread: recoursive function-is this possible??

1. ## recoursive function-is this possible??

i need to write a recoursive function that gets an integer and returns it reversed!!!
is it possible?????
here is my lousy try!! please help me!! its 4 my university and i cant find a way.
eyal.

--------------START-----------------------------------
int revnum(int num)
{
if (num/10==0)
return num%10;
else
return 10*(num%10)+revnum(num/10,dbl);
}
--------------FINISH----------------------------------

2. If you are purely using type int instead of representing the results as a string then this should be good enough:
Code:
```unsigned int revnum(unsigned int num)
{
unsigned int base = 1;

// determine the ten base value
while ((num / base) >= 10)
base*=10;

if (num >= 10)
num = ((num % 10) * base) + revnum(num/10);

return num;
}```
Of course, realize that using type unsigned int (4 bytes), restricts the size of the number you can use. If you enter a value that exceeds 4228250624, then you will get bogus data back.

David

3. ## and

if it helps at all......reverse of a number:

reverse=-num+(((num/10)-(num%10))*9)

I figured this little equation out all on my own. What do you think about it?

4. If you know how to turn a number into a string, try to figure out how to print a string backwards. Even if you don't, it's easier to think it through for a string.

Clue: if you print the letter before the recursive call, you print forwards; if you print after the call, you print backwards.

BTW, it's spelled recursive.
Good luck, Al

Popular pages Recent additions