C++ Program to reverse a given number and print it | How to reverse a given number in C++ ?

C++ Program to reverse and print the given number

        Take any integer as input from the user. Take a variable to store the reversed number. In this program, I have used the while loop, modulo, and division operator to reverse the number. 

        To know more about these operators you can visit operators in C++ and for the loop visit Loops in C++. 

        The strategy used here is a doddle. Execute the loop till the number becomes zero. Separate the last digit multiply it by 10 and add the next digit to it. 

        To separate use the modulo operator. To delete the last digit use the division operator.



Step 1 

x = Number % 10 = 5


Step 2

Reverse = Reverse * 10 + x 


Step 3

Number = Number / 10


Consider this example


Number = 195

Reverse = 0


x = 195 % 10 =  5

Reverse = 0 * 10 + 5 = 5

Number = 195 / 10 = 19


x = 19 % 10 = 9

Reverse = 5 * 10 + 9 = 59

Number = 19 / 10 = 1


x = 1 % 10 = 1

Reverse = 59 * 10 + 1 = 591

Number = 1 / 10 = 0


The number became zero execution is stopped


Code

#include <iostream>
using namespace std;


int main() {
    
    cout<<"Enter a number "<<endl;               //Requesting a Number
    int n;
    cin>>n;
    int reverse=0;                                      //To store reversed number
    
    while(n>0){                                  //loop executes till the number becomes zero
        reverse=reverse*10+n%10;            //takes last digit one by one and stores
        n=n/10;                                             //eliminates last digit
    }
    
    cout<<"Reversed Number: "<<reverse<<endl;              //Printing the reversed number
    
    return 0;
}




Sample Input: 

Enter a number 

25

Sample Output:

Reversed Number: 52

Post a Comment

0 Comments