Reversing Numbers in C++

Exercise:

Write a C++ program to reverse the number user enters.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int num, REV = 0, REM;
    cout << "Enter the numbers to be reversed:\n";
    cin >> num;
    while(num != 0)
    {
        REM = num%10;
        REV = REV*10 + REM;
        num /= 10;
    }
    cout << "After reversal: " << REV;
    return 0;
}
Click Here to View the Output:
Enter the numbers to be reversed:
5356
After reversal: 6535
Click Here to View the Explanation:
  • An input is requested from the user.
  • The input is saved as num.
  • As long as the requested variable num is not equal to 0, the while loop is iterated.
  • The formula is used to bring the right-most number to left-most 1 by 1. By dividing num by 10. The remainder is printed on the screen.