C Program to reverse a given number using Recursive function

June 5, 2021

In this tutorial, we will learn following two methods of reversing a number.
1) Using Recursion
2) Using While loop

Reverse a given number using Recursion:

In this program, we are calling a user defined function “reverse_function”, the function is calling itself recursively.

#include<stdio.h>
int main(){
   int num,reverse_number;

   //User would input the number
   printf("\nEnter any number:");
   scanf("%d",&num);

   //Calling user defined function to perform reverse
   reverse_number=reverse_function(num);
   printf("\nAfter reverse the no is :%d",reverse_number);
   return 0;
}
int sum=0,rem;
reverse_function(int num){
   if(num){
      rem=num%10;
      sum=sum*10+rem;
      reverse_function(num/10);
   }
   else
      return sum;
   return sum;
}

Output:

Enter any number: 23456
After reverse the no is :65432

Reversing a number using While loop

In the above program we learnt how to reverse a number using recursive function. Here we would learn how to do it using while loop.

#include<stdio.h>
int main()
{
   int num,rem,reverse_num=0;
   //Input number
   printf("\nEnter any number:");
   scanf("%d",&num);

   while(num>=1)
   {
      rem = num % 10;
      reverse_num = reverse_num * 10 + rem;
      num = num / 10;
   }

   printf("\nReverse of input number is: %d", reverse_num);
   return 0;
}

Output:

Enter any number: 49212
Reverse of input number is: 21294

admin