In this simple C++ program, we have to reverse a number. It is a beginner-level C++ program.
Reversing a number means swapping the places of the number. That means we are printing the number in reverse order. For example, if we have a number 1234, we have to print that as 4321 using C++.
The place value of the numbers is changed when we reverse the number.
To find the reverse of the number entered by the user in c++, first, we have to take an integer input from the user and store it in a variable n. declare an integer variable reverse and set it to 0; reverse = 0. And a variable remainder.
For reversing a number we are using the while
loop in C++. If we want to repeat something 10 times, instead of writing it 10 times, we can use a loop. The while loop
evaluates the condition. If the condition is true, the code inside the while loop body is executed. The condition is repeated and the process continues until the condition goes wrong. When the condition gets false the loop terminates.
Here, condition is n!=0;
While ( n!=0 )
{
remainder = n;
reverse = reverse * 10 + remainder;
n /= 10;
}
Print the value of reverse on the screen. And exit the program.
Step 1: Call the header file iostream.
Step 2: Use the namespace std.
Step 3: Open the main function as an integer, int main().
Step 4: Declare an integer type variable n, reverse=0, remainder.
Step 5: Print a message “Enter an integer”.
Step 6: Read the value to the variable n.
Step 7: Perform the following sub-steps until the condition 'n> 1' becomes false using the while loop
Step 8: Print the reversed number
Step 9: Exit.
#include <iostream>
using namespace std;
int main() {
int n, reverse = 0, remainder;
cout << "Enter an integer: ";
cin >> n;
while(n != 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n /= 10;
}
cout << "Reversed Number = " << reverse;
return 0;
}
Enter an integer: 5624 Reversed Number = 4265