Program to Reverse Number in C++

Here you will get program to reverse number in C++.

#include<iostream>

using namespace std;

int main()
{
	long n,rev=0,d;
	cout<<"Enter any number:";
	cin>>n;
	
	while(n!=0)
	{
		d=n%10;
		rev=(rev*10)+d;
		n=n/10;
	}
	
	cout<<"The reversed number is "<<rev;

	return 0;
}

 

Output

Enter any number:12674
The reversed number is 47621

12 thoughts on “Program to Reverse Number in C++”

    1. % is used to get remainder of a number by dividing it by other number. And if we do modulus of number by 10 then the last digit of number is remainder. Means 123%10=3 or 12%10=2. I hope this will make you clear.

    2. d is empty var, when n is suppose 123, n % 10 is takeing underoot of 123(n) by 10 and saving the remainder 3 into d for 1st loop iteration and then so on.

  1. I used this program but it is not working for numbers starting with zero.
    For example,
    001 should give me 100; but it gives me 1

    1. rev is 0 in 1st iteration so its just rev = (0 * 10) + 3;
      you can cout <<rev<<" "; below rev that youll see each iteration value of rev;

  2. anuj srivastava

    this was really helpful… thanku.. but I couldn’t find the solution to write a program to enter a number and print the sum of digits.

    1. #include
      #include
      #include
      void main()
      {
      clrscr();
      int n,x,y,sum;
      cout<>n;
      x=n%10;
      y=n/10;
      sum=x+y;
      cout<<"the sum is:"<<sum<<endl;
      getch();
      }

  3. your programs having error always
    i think u have to check them and then post ur programs………………..
    when i see ur program having error i fell veryyy fustrated …………

Leave a Comment

Your email address will not be published. Required fields are marked *