Write a C++ Program to Check Whether a Number is Palindrome or Not

A palindrome is a number that reads the same from both ends. For example, 121, 232, and 12321 are palindromes.

In this tutorial, we’ll write a C++ program to check whether a given number is a palindrome or not.

We can solve this problem by reversing the digits of the given number and comparing it with the original number.

If the reversed number is equal to the original number, then the number is a palindrome; otherwise, it’s not.

Here’s the C++ code to check whether a number is a palindrome or not:

#include <iostream>
using namespace std;

int main() {
    int n, rev = 0, rem, temp;
    cout << "Enter a number: ";
    cin >> n;
    temp = n;
    while (temp != 0) {
        rem = temp %% 10;
        rev = rev * 10 + rem;
        temp = temp / 10;
    }
    if (n == rev) {
        cout << n << " is a palindrome" << endl;
    } else {
        cout << n << " is not a palindrome" << endl;
    }
    return 0;
}

Let’s go through the code step by step:

  • We start by including the iostream header, which provides input and output streams for C++.
  • We declare the main function and some variables to hold the number to be checked (n), the reversed number (rev), and some temporary variables (rem and temp).
  • We prompt the user to enter a number using cout and read it from the console using cin.
  • We assign the value of n to temp so that we can manipulate temp without losing the original value of n.
  • We use a while loop to reverse the digits of temp and store the result in rev. We do this by taking the remainder of temp when divided by 10 (rem), multiplying rev by 10 and adding rem to it, and then dividing temp by 10 to remove the last digit.
  • Once the loop is finished, we compare n with rev. If they are equal, we print a message saying that the number is a palindrome; otherwise, we print a message saying that it’s not.

That’s it! You can now compile and run the code to check whether a given number is a palindrome or not.