Q:

C program to reverse a number using Recursion

belongs to collection: C programs - Recursion

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C program to reverse a number using Recursion - Source code

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< C program to perform Binary Search using Recursion...