In this tutorial, you will learn how to write a C++ Program to read a number from user, and check if this number is a Palindrome or not.
C++ Palindrome Number
A number is a Palindrome, if this numeric value and its reversed value are same.
Program
In the following program, we read a number into n
, and check if this number n
is a Palindrome or not.
main.cpp
</>
Copy
#include <iostream>
using namespace std;
int main() {
int n, reversed = 0;
cout << "Enter a number : ";
cin >> n;
//reverse n and store in reversed
int remainder;
int n_temp = n;
while(n_temp != 0) {
remainder = n_temp % 10;
reversed = reversed * 10 + remainder;
n_temp /= 10;
}
cout << "Given Number : " << n << endl;
cout << "Reversed Number : " << reversed << endl;
//check if n equals reversed
if (n == reversed) {
cout << "The number is a Palindrome." << endl;
} else {
cout << "The number is not a Palindrome." << endl;
}
}
Output
Enter a number : 123454321
Given Number : 123454321
Reversed Number : 123454321
The number is a Palindrome.
Program ended with exit code: 0
Enter a number : 123456789
Given Number : 123456789
Reversed Number : 987654321
The number is not a Palindrome.
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to check if given number is a Palindrome or not.