Program to Check if a Number is a Palindrome in C++
Palindrome Number
A palindrome number is a number that remains the same when its digits are reversed. For example, 121 and 1331 are palindrome numbers.
We will explore a method to check if a number is a palindrome using C++ programming.
Method: Using a while Loop
We reverse the number and compare it with the original number.
#include <iostream>
using namespace std;
int main() {
int num, originalNum, reversed = 0, digit;
// Prompt user for input
cout << "Enter a number: ";
cin >> num;
originalNum = num; // Store original number
// Loop to extract and reverse digits
while (num > 0) {
digit = num % 10; // Extract last digit
reversed = reversed * 10 + digit; // Construct reversed number
num /= 10; // Remove last digit from number
}
// Check if original and reversed numbers are the same
if (originalNum == reversed)
cout << originalNum << " is a palindrome number";
else
cout << originalNum << " is not a palindrome number";
return 0;
}
Output:
Enter a number: 121 121 is a palindrome number