C++ Program to reverse and print the given number
Take any integer as input from the user. Take a variable to store the reversed number. In this program, I have used the while loop, modulo, and division operator to reverse the number.
To know more about these operators you can visit operators in C++ and for the loop visit Loops in C++.
The strategy used here is a doddle. Execute the loop till the number becomes zero. Separate the last digit multiply it by 10 and add the next digit to it.
To separate use the modulo operator. To delete the last digit use the division operator.
Step 1
x = Number % 10 = 5
Step 2
Reverse = Reverse * 10 + x
Step 3
Number = Number / 10
Consider this example
Number = 195
Reverse = 0
x = 195 % 10 = 5
Reverse = 0 * 10 + 5 = 5
Number = 195 / 10 = 19
x = 19 % 10 = 9
Reverse = 5 * 10 + 9 = 59
Number = 19 / 10 = 1
x = 1 % 10 = 1
Reverse = 59 * 10 + 1 = 591
Number = 1 / 10 = 0
The number became zero execution is stopped
0 Comments