C Program to reverse the digits of a given number.

C Program to reverse a given number using Recursive function.

1) Using Recursion
2) Using While loop

#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;
}


Reversing a number using the While loop
  • In the above program, we learned how to reverse a number using a recursive function. Here we would learn how to do it using a 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;
}

Expected Output:

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

Post a Comment

Previous Post Next Post