We can reverse a number in C++ using loop and arithmetic operators. In this program, we are getting number as input from the user and reversing that number.
Let’s see a simple C++ example to reverse a given number.
Solution 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include<iostream> #include<iostream> using namespace std; int main() { int number, reverse = 0; cout<<"Enter a Number to Reverse and press Enter: "; cin>> number; // Taking Input Number in variable number while( true ) { if(number==0){ break; } reverse = reverse * 10; reverse = reverse + number%10; number = number/10; } cout<<"Reversed Number is: "<< reverse; return 0; } |
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include<iostream> #include<iostream> using namespace std; int main() { int number, reverse = 0; cout<<"Enter a Number to Reverse and press Enter: "; cin>> number; // Taking Input Number in variable number for( ; number!= 0 ; ) { reverse = reverse * 10; reverse = reverse + number%10; number = number/10; } cout<<"Reversed Number is: "<< reverse; return 0; } |