C++ Program to check Whether a Number is Palindrome or Not

  • Write a C++ program to check whether a number is palindrome or not.

Before jumping to a C++ program to check whether a number is palindrome or not, here is a brief overview of palindrome numbers.
A number is palindrome, if number remains same after reversing it's digits.

For Example:
1234321 is palindrome number, but 123456 is not a palindrome number.

To check whether N is palindrome number or not, first of all we have to reverse the sequence of digits of N and then compare it with original N. If both are equal then N is palindrome number.

Algorithm to check a number is palindrome or not
  • Take a number as input from user and store it in an integer variable(Let's call it inputNumber).
  • Reverse the digits of inputNumber, and store it in another integer variable(Let's call it reverseNumber).
  • Compare inputNumber and reverseNumber.
  • If both are equal then inputNumber is palindrome number otherwise not a palindrome number.

C++ program to check palindrome number

#include <iostream>

using namespace std;
 
int main(){
    int inputNumber, reverseNumber = 0, rightDigit, temp;
    cout << "Enter a number\n";
    cin >> inputNumber;
    
    temp = inputNumber;
    // reverse inputNumber and store it in reverseNumber
    while(temp != 0){
        rightDigit = temp % 10;
        reverseNumber = (reverseNumber * 10) + rightDigit;
        temp = temp/10;
    }
    // If input Number and reverse Number are same 
 // then palindrome othrwise not
    if(reverseNumber == inputNumber){
        cout << inputNumber << " is Palindrome Number";
    } else {
        cout << inputNumber << " is not a Palindrome Number";
    }
     
    return 0;
}
Output
Enter a number
1234321
1234321 is Palindrome Number
Enter a number
123456
123456 is not a Palindrome Number

In above program, we first take a number as input from user using cin and store it in variable original. Copy the value of original variable to another variable copy. Then using a while loop, we reverse the sequence of digits of a number. Finally, we compare reverse and original number. If both are equal then input number is palindrome otherwise not a palindrome number.