Reverse a Number

Program to reverse the digits of a number

C++Beginner
C++
#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

Reverse a Number in C++

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.

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)

Understanding the Algorithm

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

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

Iteration 2:

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

Iteration 3:

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

Iteration 4:

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

Result: reversed = 4321

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