C Program to reverse a given number

By | August 23, 2020

In this example, you will learn to reverse the given number using these two methods.

Examples :

Input : 123
Output : 321

Input : 1995
Output : 5991 

Approach used :

We can reverse a number in c using loop and arithmetic operators.

  1. Take input number
  2. Find its quotient and remainder.
  3. Multiply the separate variable with 10 and add the obtained remainder to it.
  4. Do step 2 again for the quotient step 3 for the remainder obtained in step 4.
  5. Repeat the process until quotient becomes zero.
  6. When it becomes zero, print the output and exit.

Implementation :

1. Using while loop

// reverse a number using while loop
#include<stdio.h>

int main()
{
   // take input
   int num = 123;
   
   int rem, reverse_num=0;
 
   // while loop 
   while(num>=1)
   {
       // find reminder with num 10
       // it finds last digit of number each time
      rem = num % 10;
      
      // this appending these reminders from LSB to MSB
      reverse_num = reverse_num * 10 + rem;
      
      // this truncate last digit of number
      num = num / 10;
   }

   // now, print reversed number of that number
   printf("Reverse of input number is: %d", reverse_num);
   
   // successful completion
   return 0;
}

Output :

Reverse of input number is: 321 

2. Using recursive program

// recursive program to reverse a number
#include<stdio.h>

// take initial reveresed number 
// and reminder variable
int sum=0, rem;

int reverse_function(int num){
    
   if(num){
       
       // find reminder with num 10
       // it finds last digit of number each time
      rem=num%10;
      
      // this appending these reminders from LSB to MSB
      sum=sum*10+rem;
      
      // call this function again 
      // after truncate last digit of number
      reverse_function(num/10);
   }
   else
   
      // else return 
      return sum;
      
    // return   
   return sum;
}

int main(){
    
    // take input
   int num = 123;
   
   int reverse_number;

   // call user defined function to perform reverse
   reverse_number=reverse_function(num);
   
    // now, print reversed number of that number
   printf("Reverse of input number is: %d", reverse_number);
   
   // successful completion
   return 0;
}

Output :

Reverse of input number is: 321 



Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.