Google News
logo
C++ Program to Reverse a Number
In the following example of C++ program to reverse a number :
Program :
#include <iostream>

int main() {
    int num, reversedNum = 0, remainder;
    std::cout << "Enter an integer: ";
    std::cin >> num;
    while (num != 0) {
        remainder = num % 10;
        reversedNum = reversedNum * 10 + remainder;
        num /= 10;
    }
    std::cout << "Reversed number: " << reversedNum << std::endl;
    return 0;
}
Output :
Enter an integer: 2345678
Reversed number: 8765432
* This program takes an input from the user num, which represents the number they want to reverse. It then uses a while loop to repeatedly extract the rightmost digit of num, add it to the reversedNum variable, and remove it from num until num is equal to 0.

* For each iteration of the loop, the program calculates the remainder of num when divided by 10 using the modulus operator (%). This gives the rightmost digit of num.

* The program then multiplies reversedNum by 10 and adds remainder to it, effectively "shifting" the digits of reversedNum one place to the left and appending remainder to the rightmost position.

* Finally, the program outputs the reversed number to the console using std::cout.