C++ program to check palindrome number

In this example, you are going to learn about C++ program to check palindrome number using the while loop and if statement.

C++ program to check palindrome number

A number is said to be a palindrome if the number remains same after reversing its digits.

For example: 121, 1001, 12321, …

Logic of the program:

First, reverse the number entered by the user and then compare with the original number.

Reversing the number:

Number: 121
reverse = 0

remainder = 121 % 10 = 1    //num % 10
reverse = (0 * 10) + 1 = 1  //(reverse * 10) + remainder
num = 121 / 10 = 12         //num = num / 10

remainder = 12 % 10 = 2
reverse = (1 * 10) + 2 = 12
num = 12 / 10 = 1

remainder = 1 % 10 = 1
reverse = (12 * 10) + 1 = 121
num = 1 / 10 = 0

Example: C++ program to check palindrome number

//C++ program for palindrome numbers
#include<iostream>
using namespace std;

int main()
{
   int num, reverse = 0, remainder, temp;
   // reverse is used to store to reverse number
   cout << "Enter the number: ";
   cin >> num;

   temp = num; // original number is stored in temp variable

   while( temp != 0)
   {
      remainder = temp % 10;
      reverse = reverse * 10 + remainder;
      temp = temp / 10;
   }

   cout << "Reversed number: " << reverse << endl;

   if (num == reverse) // checking whether num is equal to reverse
      cout << "\n" << num << " is a palindrome number." << endl;
   else
      cout << "\n" << num << " is not a palindrome number." << endl;
   return 0;
}

Output

Enter the number: 121
Reversed number: 121

121 is a palindrome number.

Enter the number: 1231
Reversed number: 1321

1231 is not a palindrome number.

Explanation

In the above program, reverse of the number entered by the user is calculated inside while loop which iterates till the value of temp is equal to zero.

After calculating the reverse number, if condition is used for comparison.