Q:

C program to reverse an integer number using recursion

0

C program to reverse an integer number using recursion

 

All Answers

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

The source code to reverse an integer number using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to reverse an integer number using recursion

#include <stdio.h>
#include <math.h>

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

int main()
{
    int num = 0;
    int reverse = 0;
    int len = 0;
    int temp = 0;

    printf("Enter Number: ");
    scanf("%d", &num);

    temp = num;
    while (temp > 0) {
        temp = temp / 10;
        len = len + 1;
    }

    reverse = reverseNum(num, len);
    printf("Reverse number is: %d", reverse);

    return 0;
}

Output:

RUN 1:
Enter Number: 12345
Reverse number is: 54321

RUN 2:
Enter Number: 362436
Reverse number is: 634263

RUN 3:
Enter Number: 8
Reverse number is: 8

RUN 4:
Enter Number: 19
Reverse number is: 91

Explanation:

In the above program, we created two functions reverseNum() and main() function. The reverseNum() function is a recursive function, which is used to reverse a given integer number and return the result to the calling function.

In the main() function, we read an integer number from the user and then reverse the given number using the reverseNum() function and printed the result on the console screen.

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

total answers (1)

C program to check a given number is prime or not ... >>
<< C program to calculate length of the string using ...