Write a C++ Program to Reverse a Number

Reversing a number in C++ is a simple task that involves manipulating the digits of a given number to obtain a reversed version of the original number.

The basic approach is to extract each digit of the number, from the least significant digit to the most significant digit, and then reconstruct the reversed number by appending each digit in reverse order.

To reverse a number in C++, we can use the following steps:

  • Declare an integer variable to store the number to be reversed and read its value from the user.
  • Initialize a variable to store the reversed number as 0.
  • Using a while loop, extract the least significant digit of the number by performing a modulo operation with 10, and add it to the reversed number after shifting the digits of the reversed number one position to the left.
  • Divide the original number by 10 to discard the least significant digit.
  • Repeat steps 3-4 until all the digits of the original number have been extracted and added to the reversed number.
  • Output the reversed number to the user.

The following is the C++ code that implements the above algorithm:

#include <iostream>
using namespace std;

int main()
{
    int num, rev = 0;
    cout << "Enter a number: ";
    cin >> num;
    while (num > 0)
    {
        rev = (rev * 10) + (num %% 10);
        num = num / 10;
    }
    cout << "The reversed number is: " << rev;
    return 0;
}

In the above code, the variable num stores the original number and rev stores the reversed number.

The while loop extracts each digit of num and adds it to rev after shifting the digits of rev one position to the left.

The division by 10 discards the least significant digit of num, and the loop continues until all the digits of num have been extracted and added to rev.

Finally, the reversed number is output to the user.

In conclusion, reversing a number in C++ is a simple task that involves extracting each digit of the number and appending it in reverse order to obtain the reversed number.

The above algorithm can be easily implemented in C++ using a while loop and basic arithmetic operations.