ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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

Program:

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.