adplus-dvertising

C program to reverse a number using Recursion

frame-decoration

C program to reverse a number using Recursion

Problem Description

The following C program using recursion reverses the digits of the number and displays it on the output of the terminal. For example, 12345 becomes 54321.

C program to reverse a number using Recursion - Source code
     
                
  /*
 * C program to find the reverse of a number using recursion
 */
#include <stdio.h>
#include <math.h>

int reverse(int, int);

int main()
{
    int n, result;
    int len = 0, temp;

    printf("Enter an integer number to reverse: ");
    scanf("%d", &n);
    temp = n;
    while (temp != 0)
    {
        len++;
        temp = temp / 10;
    }
    result = reverse(n, len);
    printf("The reverse of %d is %d.\n", n, result);
    return 0;
}

int reverse(int n, int len)
{
    if (len == 1)
    {
        return n;
    }
    else
    {
        return (((n % 10) * pow(10, len - 1)) + reverse(n / 10, --len));
    }
}

     
      

Program Output

Enter an integer number to reverse: 123547
The reverse of 123547 is 745321.