Recursive program to reverse a number

Recursive program to reverse a number

Given a number , write a Recursive program to reverse a number .

Sample input:-

253

Sample output:-

Reverse of 253 is  352

Recursive program to reverse a number:-

The objective of this code is to reverse the number .

Method 1:-

In this method we will create a function ReverseNumber()  in which we will pass two parameter first for number and second for the Reverse number . In second parameter we will store the final and i.e reverse of the number . And the base case for this function is if n==0 the return second parameter.

C Code:-

```#include<stdio.h>

// recursive function to reverse the number
int ReverseNumber(int n, int reverse)
{
if(n==0)
return reverse;
else
{
int r=n%10;
n=n/10;
reverse=reverse*10+r;
return ReverseNumber(n,reverse);
}
}

// Driver function
int main()
{
int n;
printf("Enter a number\n");
scanf("%d",&n);
printf("Reverse of %d is %d ",n,ReverseNumber(n,0));
return 0;
}```

Output:-

```Enter a number
256
Reverse of 256 is 652```

Method 2:-

In this method instead of using the second parameter we will use a global variable Rev_num for storing the reverse of the number.

```#include<stdio.h>

int Rev_num=0;
// recursive function to reverse the number
void ReverseNumber(int n)
{
if(n)
{
int r=n%10;
Rev_num=Rev_num*10+r;
n=n/10;
ReverseNumber(n);
}

}

// Driver function
int main()
{
int n;
printf("Enter a number\n");
scanf("%d",&n);
ReverseNumber(n);
printf("Reverse of %d is %d ",n,Rev_num);
return 0;
}```

Output:-

```Enter a number
256
Reverse of 256 is 652```