Reverse a Number

How to Reverse a Number in C++ (6 Programs With Output)

BeginnerTopic: Advanced Number 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 teaches you how to reverse a number in C++. Reversing a number means reading its digits from right to left instead of left to right. For example, reversing 1234 gives 4321. This is a common programming problem that helps you understand digit manipulation, loops, and number operations.

---

1. What This Program Does

The program takes a number and reverses its digits. For example:

Input: 1234
Output: 4321

The process involves extracting digits from the right (one's place, ten's place, etc.) and building a new number from left to right.

Example:

1234 reversed = 4321
567 reversed = 765
100 reversed = 1 (leading zeros are dropped)

---

2. Header File Used

This header provides:

cout for displaying output
cin for taking input from the user

---

#include <iostream>

3. Declaring Variables

The program declares:

int num, reversed = 0, remainder;

num stores the original number entered by the user.
reversed stores the reversed number (initialized to 0).
remainder stores the last digit extracted in each iteration.

---

4. Taking Input From the User

The program asks:

cin >> num;

The user enters a number, for example: 1234

We also save the original:

int original = num;

This is important because we'll modify num during the reversal process, and we need the original value for display.

---

cout << "Enter a number: ";

5. The Reversal Algorithm (While Loop Method)

The core logic uses a while loop:

while (num != 0) {

remainder = num % 10;

reversed = reversed * 10 + remainder;

num /= 10;

}

Let's break down how this works step-by-step for num = 1234:

Step 1:

remainder = 1234 % 10 = 4 (extract last digit)
reversed = 0 * 10 + 4 = 4
num = 1234 / 10 = 123 (remove last digit)

Step 2:

remainder = 123 % 10 = 3
reversed = 4 * 10 + 3 = 43
num = 123 / 10 = 12

Step 3:

remainder = 12 % 10 = 2
reversed = 43 * 10 + 2 = 432
num = 12 / 10 = 1

Step 4:

remainder = 1 % 10 = 1
reversed = 432 * 10 + 1 = 4321
num = 1 / 10 = 0

Step 5:

num is now 0, so the loop stops
Final result: reversed = 4321

---

6. Understanding the Key Operations

Modulo Operator (%)

:

num % 10 gives the last digit of the number.
Example: 1234 % 10 = 4, 123 % 10 = 3

Integer Division (/)

:

num / 10 removes the last digit.
Example: 1234 / 10 = 123, 123 / 10 = 12

Building the Reversed Number

:

reversed = reversed * 10 + remainder
This shifts existing digits left and adds the new digit on the right.
Example: If reversed = 43 and remainder = 2, then 43 * 10 + 2 = 432

---

7. Other Methods (Mentioned but not shown in code)

Method 2: Using For Loop

int reversed = 0;

for (int temp = num; temp != 0; temp /= 10) {

reversed = reversed * 10 + (temp % 10);

}

Similar logic but uses for loop instead of while.
Same algorithm, different loop structure.

Method 3: Using Recursion

int reverseRecursive(int num, int rev = 0) {

if (num == 0) return rev;

}

Recursive approach - function calls itself.
Base case: when num becomes 0, return the reversed number.
Recursive case: extract digit and build reversed number.
    return reverseRecursive(num / 10, rev * 10 + num % 10);

Method 4: Using String Conversion

string str = to_string(num);

reverse(str.begin(), str.end());

int reversed = stoi(str);

Convert number to string.
Reverse the string.
Convert back to integer.
Simple but less efficient.

Method 5: Using Stack

stack<int> digits;

while (num != 0) {

digits.push(num % 10);

num /= 10;

}

int reversed = 0, place = 1;

while (!digits.empty()) {

reversed = reversed * 10 + digits.top();

digits.pop();

}

Uses stack's LIFO (Last In First Out) property.
Push digits onto stack, then pop to build reversed number.

Method 6: Using Array

int digits[10], count = 0;

while (num != 0) {

digits[count++] = num % 10;

num /= 10;

}

int reversed = 0;

for (int i = 0; i < count; i++) {

reversed = reversed * 10 + digits[i];

}

Store digits in an array.
Build reversed number from array.

---

8. Displaying the Result

The program prints:

Output:

Reverse of 1234 is: 4321

We use original (not num) because num was modified during the reversal process.

---

cout << "Reverse of " << original << " is: " << reversed << endl;

9. Edge Cases and Special Numbers

Zero

:

Input: 0
Output: 0 (correct - zero reversed is still zero)

Single Digit

:

Input: 5
Output: 5 (single digit reversed is itself)

Numbers Ending in Zero

:

Input: 100
Output: 1 (leading zeros are dropped - this is correct for integers)

Negative Numbers

:

This program doesn't handle negatives.
To handle: check if negative, reverse absolute value, add negative sign.

Very Large Numbers

:

May cause integer overflow if reversed number is too large.
Consider using long long for larger numbers.

---

10. When to Use Each Method

-

While Loop

: Best for most cases - simple, efficient, easy to understand.

-

For Loop

: Alternative to while loop - same efficiency, different style.

-

Recursion

: Educational - helps understand recursive thinking.

-

String Conversion

: Simple but less efficient - good for learning string operations.

-

Stack

: Demonstrates stack usage - educational purpose.

-

Array

: Shows array manipulation - useful for learning arrays.

Best Practice

: Use the while loop method for most applications - it's efficient and straightforward.

---

11. Common Use Cases

Palindrome Checking

:

Reverse a number and compare with original.
If same, it's a palindrome (e.g., 121, 1331).

Number Manipulation

:

Extracting digits for various operations.
Building numbers from digits.

Algorithm Practice

:

Common interview question.
Helps understand digit manipulation.
Foundation for more complex number problems.

---

12. Important Considerations

Integer Overflow

:

Reversing very large numbers may exceed int range.
Example: Reversing 2147483647 (max int) gives 7463847412 (too large).
Solution: Use long long for larger numbers.

Leading Zeros

:

Integers cannot have leading zeros.
Reversing 100 gives 1 (not 001).
This is correct behavior for integers.

Negative Numbers

:

This implementation doesn't handle negatives.
To handle: process absolute value, then add sign.

---

13. return 0;

This ends the program successfully.

---

Summary

Reversing a number extracts digits from right to left and builds a new number.
The while loop method is most common: extract last digit (%), remove it (/), build reversed number.
Modulo (%) extracts last digit, division (/) removes last digit.
Other methods include recursion, string conversion, stack, and array approaches.
Consider integer overflow for very large numbers.
Leading zeros are automatically dropped in integer representation.
Understanding number reversal is essential for many number manipulation problems.

This program is fundamental for beginners learning digit manipulation, understanding modulo and division operations, and preparing for more complex number-related algorithms in C++ programs.

Let us now understand every line and the components of the above program.

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.

Practical Learning Notes for Reverse a Number

This C++ program is part of the "Advanced Number Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents