C Program to Reverse Number Using Recursion
Problem: Write a C program to reverse given number using recursion.
Now we will reverse a number without using loop, that we will use the concept of recursion here. We will reverse a number using recursive function.
Now we will reverse a number without using loop, that we will use the concept of recursion here. We will reverse a number using recursive function.
C program to reverse a number using recursion
/* Aim: C program to find the reverse of a number using recursion */
#include <stdio.h>
#include <math.h>
void rev(int, int);
int main()
{
int num, result;
int length = 0, temp;
printf("Enter an integer number to reverse: ");
scanf("%d", &num);
temp = num;
while (temp != 0)
{
length++;
temp = temp / 10;
}
result = rev(num, length);
printf("The reverse of %d is %d.\n", num, result);
return 0;
}
void rev(int num, int len)
{
if (len == 1)
{
return num;
}
else
{
return (((num % 10) * pow(10, len - 1)) + rev(num / 10, --len));
}
}
/* Output of above code:-
Enter an integer number to reverse: 1234
The reverse of 1234 is 4321.
*/