C Program to Reverse Given Number with explanation

Ans: 

In this tutorial, we are going to learn how to write a program to reverse the digits of a given number using a C programming language.

So Let’s Begin

Before directly moving on writing reverse program in C, first you should understand what logic we are going to use to achieve it.

Suppose if someone gives input 123, then our program should provide output 321.

The logic behind it is

First, we will find the last digit of input number, and then we will store it into a variable and remove it. Now again, we will see that the second last digit will become the last digit. So again we will pick the last digit of the number and then append it with the digit which we have calculated and stored previously in ‘reverse’ variable. We will follow the same approach for all digit of a number. Once we apply the same logic for each digit of number then at last ‘reverse’ variable will contain a reverse number.

Below we will see it with the help of the program

C program to reverse a number

#include <stdio.h>
int main()
{    
	int n=321,reverse=0;  
	printf("before reverse = %d",n);
	while(n!=0){        
		reverse = reverse*10 + n%10;        
		n=n/10;    
	}
	printf("\nafter reverse = %d",reverse);    
	return 0;
} 

Output:

before reverse = 321
after reverse = 123

Explanation of reverse program in c

  • In the above program I have taken a static number 321 which is assigned in variable ‘n’. Here I am not taking the value from users.
  • We have one more integer variable  ‘reverse’ that will store value each time when we find last digit of the number.
  • We can say that ‘n’ is storing original value and ‘reverse’ variable will store the value after reverse.
  • Now using while loop here we are checking that value of ‘n’ should not be 0. If already zero then we can’t perform any operation on it.
  • And when ‘n’ is not zero, in body of while loop we are finding last digit of the number and adding it to the same number by multiplying 10 and then storing it in reverse variable.
  • And at last dividing original number by 10 to remove the last digit of the number. As we already collected it in reverse variable.

I hope you have understand it well.

Thank you.

Watch here the Explanation of reverse program in C

Leave a Comment