Reverse a Number in C++ Program Code


Levels of difficulty: / perform operation:

A simple C++ program in which user enter a number, program reverse it and display reversed number on the console.
For example: If input number is 12345
Then reversed number will be 54321

Logic Explanation:
To make a program like that we need to access every digit individually of entered number from last
Modulus operator provides such condition so first we take modulus of number until it become zero and add the every single digit which produce by modulus operator into our new integer variable which is named as reverse in the program with at each iteration of for loop
When for loop is break variable revers will have the reverse of entered number



C++ Program

#include<iostream>
using namespace std;
int main() {
	int number, reverse = 0;
	cout<<"Input 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<<"New Reversed Number is:  "<<reverse;
	return 0;
}