×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to reverse an integer number using recursion

Here, we are going to learn how to reverse an integer number using recursion in C programming language?
Submitted by Nidhi, on July 09, 2021

Problem statement

Here, we will read an integer number from the user and then reverse the given number using a recursive function.

C program to reverse an integer number using recursion

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.

C Recursion Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.