Palindrome Check in C++
Check whether a number reads the same forwards and backwards in C++ by reversing its digits and comparing. Traces 121 and 123 and explains why 10 fails.
1#include <iostream>2using namespace std;34int main() {5 int num, reversed = 0, remainder, original;67 cout << "Enter a number: ";8 cin >> num;910 original = num;1112 // Reverse the number13 while (num != 0) {14 remainder = num % 10;15 reversed = reversed * 10 + remainder;16 num /= 10;17 }1819 if (original == reversed) {20 cout << original << " is a palindrome" << endl;21 } else {22 cout << original << " is not a palindrome" << endl;23 }2425 return 0;26}
Sample Output
121 is a palindrome
Reversed value matched the original.
In this one
- How to reuse the digit-reversal loop
- Why the original value must be kept
- How trailing zeros break numeric palindromes
- How to compare and print a yes/no result
How it works
- 1
Read 121 and keep original.
- 2
Reverse it with % 10 and / 10 to get 121.
- 3
Compare original == reversed.
- 4
Equal, so "121 is a palindrome" prints.
Edge cases
Number ending in 0
Enter 10.
Reversing gives 1, and 10 != 1, so it is not a palindrome. That is correct: 01 is not a valid integer form.
Negative number
Enter -121.
The reverse is -121 in C++ (each % 10 is negative), so the program says palindrome, though many definitions say negative numbers never are.
What's going on
A palindrome number reads the same forwards and backwards. 121 is. 123 is not. This C++ program reverses the digits and compares.
That's the same loop as Reverse a Number. The extra pieces are original and the if.
int num, reversed = 0, remainder, original;
reversed starts at 0. original will hold the value cin just gave you, because the loop wipes num.
cin >> num;
original = num;
Sample: 121. Skip this copy and after the loop num is 0, so you compare 0 to 121 and always lose.
while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}
Walk 121:
if (original == reversed)
121 == 121 → 121 is a palindrome.
123:
Single digits (7) reverse to themselves. Always palindromes.
10 is the usual trap. Reverse as an int is 1, not 01. So 10 is not a palindrome. Trailing zeros in the original become leading zeros in the reverse, and integers drop those.
Don't reverse into a string unless the homework asks for it. For a number, % 10 / / 10 is the whole trick.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Is 1221 a palindrome?
Pick an answer to check it.
Question 2
Why is original needed?
Pick an answer to check it.
Questions people ask
Are single digits palindromes?
Yes. A single digit reverses to itself.
How do I check a word?
Compare characters from both ends of a string. See Check Palindrome in the string topic.
Can reversing overflow?
For an int near the max, yes. A 10-digit number like 1999999999 reversed exceeds int.