Reverse Numbers function using recursion in C

c, function, recursion, reverse

Solution

Here's some working code:

int rev (int number){
    int base = 1;

    while (number / (base * 10)){/*
        * This calculates the base of the number
        * ie number = 435
        *    base   = 100
        */
        base *= 10;
    }

    if (number <= 9){
        return number;
    } else if (number >= 10){ // notice different expression
        int revNum = (number % 10) * base; // this was out of order
        return rev (number / 10) + revNum;
    }
}

The main reason your code couldn't work, other than what I commented above, is that `sum` isn't preserved within the calls. This is a common problem in making recursive functions.

To remedy this, the "base" is calculated each function call, instead of having a fixed value. This also a bit better because it allows larger numbers to be passed, instead of ones not bigger than `100` (another limit of the code you've chosen).

Another implementation is to base the base as a second parameter, so that it doesn't have to be recalculated every function call. This can, however, be easily remedied by a simple macro. The call may be :

int rev_number (int number, int base){ .. }

But a can be conveniently placed in a macro (or other function call):

#define rev(num) rev_number (number, 0)

This is a little more efficient, but the difference may or may not be important.

Problem

The following is a function that is meant to return the reverse of a number using recursion. However, it only returns the last digit of the number. I'd like to know why and how to fix it? ``` int rev(int number) { int revNum=0, sum=100; if(number<=9) return(number); else if(number>0) { return(rev(number/10)+revNum); revNum=(number%10)*sum; sum=sum/10; } } ``` Thank you!!!

Original source