C program to find reverse of a number using recursion

Write a recursive function in C programming to find reverse of any number. How to find reverse of any number in C programming using recursion. Finding reverse of any number using recursion in C programming.

Input number: 12345
Output reverse: 54321

Required knowledge

Basic C programming, Function, Recursion

Logic to find reverse of number using recursion

We have already seen how to find reverse of any number using simple loops here we will see how efficiently we can find reverse of any given number using recursion. If you have gone through the reverse procedure through loop you probably know that reversing procedure includes four basic steps i.e.
  1. Multiply the rev variable by 10.
  2. Find the last digit of the given number.
  3. Add the last digit just found to rev.
  4. Divide the original number by 10 to eliminate the last digit, which is not needed anymore.
And we repeat the above four steps till the number becomes 0 and we are left with the reversed number in rev variable. Here also we will use the above four steps to find the reverse using recursive approach with the given base condition:
reverse(0) = 0 {Base condition}
reverse(n) = (n%10 * pow(10, digits)) + reverse(n/10) {where digit is the total number of digits in number}

Program to find reverse using recursion

 * C program to find reverse of any number using recursion
#include <stdio.h>
#include <math.h>

/* Fuction declaration */
int reverse(int num);

int main()
    int num, rev;

    /* Reads number from user */    
    printf("Enter any number: ");
    scanf("%d", &num);
    /*Calls the function to reverse number */
    rev = reverse(num); 
    printf("Reverse of %d = %d", num, rev);
    return 0;

 * Recursive function to find reverse of any number
int reverse(int num)
    int digit;
    //Base condition
        return 0;
    //Finds total number of digits
    digit = (int)log10(num);
    return ((num%10 * pow(10, digit)) + reverse(num/10));

Enter any number: 12345
Reverse of 12345 = 54321

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment