Write a recursive function which given an integer n, prints it with its digits reversed. E.g given 23998, it prints 89923.

Source Code

Brief explanation is provided after the source code.

 
#include <stdio.h>


long reverse(long);

int main(int argc, char ** argv) {

    long n;
    printf("Input an integer: ");
    scanf("%ld", &n);
    printf("Reversed: %ld\n", reverse(n));
    return 0;

}

long reverse(long n) {

    static long r = 0;

    if (n == 0)
        return 0;

    r = r * 10;
    r = r + n % 10;
    reverse(n/10);
    return r;
}

When you compile and execute the above program it produces the following result on Linux:

Input an integer: 23998
Reversed: 89932

Brief Explanation

  • The program starts by requesting the user to input an integer.
  • Next, the inputted integer is passed to the recursive function reverse which reverses its digits.
  • A recursive function is a function that calls itself during its execution. This enables the function to repeat itself several times, outputting the result at the end of each iteration. More on Recursive Function
  • The return value of zero in the main function implies normal termination; non-zero values signal unusual or erroneous termination conditions.

Add comment


Security code
Refresh