How to Reverse A Number in C++

Introduction:

The program given below is made to reverse the number. For example if number entered by user is 567 then program will reverse it to 765.

C++ Code:

Program Logic:

  • To reverse a number, it is necessary to have access to every digit individually of entered number.
  • This program uses while loop to access every digit of number.
  • We used Modulus Operator to extract digits one by one from number and added extracted digits to reverse variable.
  • Number is divided by 10 so for next loop iteration it will point to next digit.
  • Reverse number is multiplied by 10 so digits extracted will be placed one place further. If we don’t do this then digits will be added up to produce sum.
  • After the breakage of loop, all the digits are accumulated in reverse order in reverse variable.

Dry Run:

When number=4567

reverse=0*10=0
reverse=0+(4567%10)=0+7=7
number=4567/10=456

When number=456

reverse=7*10=70
reverse=70+(456%10)=70+6=76
number=456/10=45

When number=45

reverse=76*10=760
reverse=760+(45%10)=760+5=765
number=45/10=4

When number=4

reverse=765*10=7650
reverse=7650+(4%10)=7650+4=7654
number=4/10=0

Program Output:

reverse a number in c++Thanks for reading this article. If you have any question then you can ask me in comments.

You can also Click Here To Download Exercise Files.