Reverse a Number

Program to reverse the digits of a number

BeginnerTopic: Loop Programs
Back

C++ Reverse a Number Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int num, reversed = 0, remainder;
    
    cout << "Enter a number: ";
    cin >> num;
    
    int original = num;
    
    while (num != 0) {
        remainder = num % 10;
        reversed = reversed * 10 + remainder;
        num /= 10;
    }
    
    cout << "Reverse of " << original << " is: " << reversed << endl;
    
    return 0;
}
Output
Enter a number: 1234
Reverse of 1234 is: 4321

Understanding Reverse a Number

This program reverses a number using a while loop. We extract the last digit using modulo (%), add it to the reversed number (multiplied by 10), and remove the last digit from the original number using integer division (/). This process continues until the number becomes 0.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents