C program to find reverse of a number using recursion

In this blog post, we learn how to write a C program to find reverse of a number using recursion?Write a recursive function in C programming to find the reverse of a number. How to find reverse of a number in C programming using recursion. Logic to find reverse of a number using recursion in C programming. Let’s see an example,

 

Input : num = 12345
Output : 54321


Input : num = 876
Output : 678

 

C Program to find reverse of a number using a recursive function:

 

#include <stdio.h>;

//Recursive function to
//reverse digits of number
int reversDigits(int num)
{
    static int rev_num = 0;
    static int base_pos = 1;
    if(num > 0)
    {
        reversDigits(num/10);
        rev_num += (num%10)*base_pos;
        base_pos *= 10;
    }
    return rev_num;
}

int main()
{
    int number, reversed = 0;

    //Input a number from user
    printf("Enter any number = ");
    scanf("%d", &number);

    reversed = reversDigits(number);

    printf("Reverse of no. is %d", reversed);

    return 0;
}

Output:

Enter any number = 12345
Reverse of no. is 54321

 

The above program works fine for a positive number but it will not work for the negative number. So for a negative number, we need to modify the logic slightly. Let see another example code to get reverse of the negative number using recursion.

 

 

C Program to reverse a negative number using recursion:

Similar to positive number we can find the reverse of a negative number. Here we will use same function which I have used for the positive number. In addition, check, if the number is negative then convert it to positive and then pass it to reverse() function (Used for positive number). One more condition you need to check, if the number was negative then convert the reversed number to negative.

#include <stdio.h>;

//Recursive function to
//reverse digits of number
int reversDigits(int num)
{
    static int rev_num = 0;
    static int base_pos = 1;
    if(num > 0)
    {
        reversDigits(num/10);
        rev_num += (num%10)*base_pos;
        base_pos *= 10;
    }
    return rev_num;
}

int main()
{
    int number, reversed = 0, tmp;

    //Input a number from user
    printf("Enter any number = ");
    scanf("%d", &number);

    //If number is negative, then convert it to positive
    tmp = (number < 0)?(-1 * number): number;

    //Reverse the number
    reversed = reversDigits(tmp);

    //If number was negative, then convert the reverse to negative
    reversed = (number < 0)? (-1 * reversed): reversed;

    printf("Reverse of no. is %d", reversed);

    return 0;
}

Output:

Enter any number = -12345
Reverse of no. is -54321