C++ Program to Reverse a Number

1. Introduction

Reversing a number involves transposing its digits in the opposite order. For example, if the given number is 12345, its reversed form will be 54321. In this blog post, we will walk you through a C++ program to reverse any given number.

2. Program Overview

The process to reverse a number in C++ is straightforward:

1. Continuously divide the number by 10 to get the remainder.

2. Use this remainder as the reversed number's next digit.

3. Reduce the original number by dividing it by 10 (i.e., remove its last digit).

4. Repeat the steps until the number is 0.

The program will:

1. Prompt the user to enter a number.

2. Apply the above steps to reverse the number.

3. Display the reversed number.

3. Code Program

Here is the complete C++ program to reverse a given number:

#include <iostream>
using namespace std;

int main() {
    int num, reversedNumber = 0, remainder;

    // Prompt user for input
    cout << "Enter an integer: ";
    cin >> num;

    while(num != 0) {
        remainder = num % 10;             // Step 1: Get the last digit
        reversedNumber = reversedNumber * 10 + remainder; // Step 2: Append to reversed number
        num /= 10;                        // Step 3: Reduce the original number
    }

    // Display the result
    cout << "Reversed Number: " << reversedNumber;

    return 0;  // Indicate successful program termination
}

Output:

Enter an integer: 9876
Reversed Number: 6789

4. Step By Step Explanation

1. Headers and Namespace: We begin by including the iostream library, necessary for input-output operations, and state the use of the standard namespace.

2. Main Function: The program starts its execution here. We first prompt the user for a number. The main logic to reverse the number resides in a while loop.

3. User Input: We use cout to display a message to the user and cin to receive the number.

4. Reversal Logic: We use modulo % to obtain the last digit of the number and append it to the reversed number. We then divide the original number by 10 to remove its last digit. This process continues until the entire number is reversed.

5. Displaying the Result: We utilize cout to show the reversed number.

6. Program Termination: The program ends its execution, indicating a successful run with a return value of 0.

Comments