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 the digits of a number. For example, if you enter 1234, it becomes 4321. This program demonstrates the while loop, modulo operator (%), integer division (/), and the concept of building a number digit by digit. Understanding number reversal is important for solving palindrome problems, number manipulation, and many algorithmic challenges.

---

1. What This Program Does

The program:

Takes a number as input (e.g., 1234)
Reverses its digits (becomes 4321)
Displays the reversed number

Examples:

Input:

1234

→ Output:

4321

Input:

567

→ Output:

765

Input:

100

→ Output:

1

(leading zeros are not displayed)

This is a fundamental problem that teaches:

Digit extraction using modulo operator
Building numbers digit by digit
While loops for repetitive operations

---

2. Header File: #include <iostream>

#include <iostream>

Provides:

cout → for displaying output
cin → for reading input

---

3. Declaring Variables

int num, reversed = 0, digit;

Variable `num`:

Stores the original number entered by the user
This number will be processed and reduced to 0

Variable `reversed`:

Stores the reversed number we're building

-

Initialized to 0

We'll build the reversed number starting from 0

Variable `digit`:

Temporarily stores the last digit extracted from num
Used to extract and process each digit one by one

Why initialize reversed to 0?

We start building the reversed number from scratch
0 is the identity element for addition in building numbers
Similar to initializing sum to 0 in addition problems

---

4. Taking Input From User

`cout << "Enter a number: ";`

cin >> num;

Prompts user to enter a number
Reads and stores it in num

Example:

User enters:

1234

num = 1234

---

5. Saving Original Number

int original = num;

Why save the original?

num will be reduced to 0 during the reversal process
We need the original value to display in the output message
Example: "Reverse of 1234 is: 4321"

If we don't save it, we can't show the original number in the output.

---

6. Understanding the While Loop

while (num != 0)

How while loop works:

Checks condition: Is num not equal to 0?
If

true

, execute the loop body

If

false

, exit the loop

Unlike for loop:

While loop continues as long as condition is true
We don't know in advance how many iterations (depends on number of digits)
Perfect for this problem since we process until number becomes 0

---

7. Extracting the Last Digit

digit = num % 10;

Understanding Modulo Operator (%)

The modulo operator gives the

remainder

after division.

`num % 10` extracts the last digit:

When you divide any number by 10, the remainder is always the last digit

Examples:

1234 % 10 =

4

(remainder when 1234 ÷ 10)

567 % 10 =

7

(remainder when 567 ÷ 10)

89 % 10 =

9

(remainder when 89 ÷ 10)

5 % 10 =

5

(remainder when 5 ÷ 10)

Why this works:

1234 ÷ 10 = 123 remainder

4

→ last digit is 4

567 ÷ 10 = 56 remainder

7

→ last digit is 7

---

8. Building the Reversed Number

reversed = reversed * 10 + digit;

This is the

key line

that builds the reversed number digit by digit.

How it works:

Step 1: Multiply by 10

Shifts existing digits one place to the left
Creates space for the new digit on the right

Step 2: Add the digit

Adds the extracted digit to the rightmost position

Step-by-step execution (reversing 1234):

Initial:

num = 1234, reversed = 0

Iteration 1:

Extract: digit = 1234 % 10 = 4
Build: reversed = 0 * 10 + 4 = 4
Remove: num = 1234 / 10 = 123
Now: reversed = 4, num = 123

Iteration 2:

Extract: digit = 123 % 10 = 3
Build: reversed = 4 * 10 + 3 = 43
Remove: num = 123 / 10 = 12
Now: reversed = 43, num = 12

Iteration 3:

Extract: digit = 12 % 10 = 2
Build: reversed = 43 * 10 + 2 = 432
Remove: num = 12 / 10 = 1
Now: reversed = 432, num = 1

Iteration 4:

Extract: digit = 1 % 10 = 1
Build: reversed = 432 * 10 + 1 = 4321
Remove: num = 1 / 10 = 0
Now: reversed = 4321, num = 0

Iteration 5:

Check: num != 00 != 0

false

-

Loop stops

Final result:

reversed = 4321

---

9. Removing the Last Digit

num = num / 10;

Integer Division (/):

When dividing integers, the result is also an integer (decimal part is discarded)
This effectively removes the last digit

Examples:

1234 / 10 =

123

(not 123.4)

567 / 10 =

56

(not 56.7)

89 / 10 =

8

(not 8.9)

5 / 10 =

0

(not 0.5)

Why this works:

1234 ÷ 10 = 123.4, but integer division gives 123
The last digit (4) is effectively removed

---

10. Visual Representation

Reversing 1234:

Initial: num = 1234, reversed = 0

Iteration 1:

Extract last digit: 1234 % 10 = 4
Build reversed: 0 * 10 + 4 = 4
Remove last digit: 1234 / 10 = 123
State: num = 123, reversed = 4

Iteration 2:

Extract: 123 % 10 = 3
Build: 4 * 10 + 3 = 43
Remove: 123 / 10 = 12
State: num = 12, reversed = 43

Iteration 3:

Extract: 12 % 10 = 2
Build: 43 * 10 + 2 = 432
Remove: 12 / 10 = 1
State: num = 1, reversed = 432

Iteration 4:

Extract: 1 % 10 = 1
Build: 432 * 10 + 1 = 4321
Remove: 1 / 10 = 0
State: num = 0, reversed = 4321

Loop ends (num == 0)

Result: 4321 ✅

---

11. Displaying the Result

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

This prints:

Text: "Reverse of "
Original number: 1234
Text: " is: "
Reversed number: 4321
New line

Output:

Reverse of 1234 is: 4321

---

12. Special Cases

Case 1: Single digit number

Input:

5

Iteration 1: Extract 5, Build 5, Remove → num = 0
Output:

5

(same as input)

Case 2: Number ending with zeros

Input:

100

Iteration 1: Extract 0, Build 0, Remove → num = 10
Iteration 2: Extract 0, Build 0, Remove → num = 1
Iteration 3: Extract 1, Build 1, Remove → num = 0
Output:

1

(leading zeros are not displayed)

Case 3: Palindrome number

Input:

1221

Output:

1221

(same as input - it's a palindrome!)

---

13. Why This Algorithm Works

The key insight:

Extract digits from right to left (using % 10)
Build new number from left to right (using * 10 + digit)
This naturally reverses the order

Mathematical perspective:

Original: 1234 = 1×1000 + 2×100 + 3×10 + 4×1
Reversed: 4321 = 4×1000 + 3×100 + 2×10 + 1×1

We're essentially reading digits in reverse order and building the new number.

---

Summary

Modulo operator (%) extracts the last digit
Integer division (/) removes the last digit
While loop continues until number becomes 0
Building reversed number: reversed = reversed * 10 + digit
This pattern is used in many problems: palindrome checking, number manipulation, digit extraction

This program teaches essential number manipulation skills that are crucial for:

Palindrome problems
Number system conversions
Digit manipulation algorithms
Many competitive programming problems

Understanding this algorithm helps you solve more complex problems involving number manipulation and digit processing.

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 "Loop 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