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

C++ProgrammingServer Side Programming

A palindrome number remains the same if its digits are reversed i.e its value does not change. A palindrome number can also be called symmetric. For example: The numbers 12321, 1551, 11 etc are palindromes as they do not change even if their digits are reversed.

A program that checks if a number is palindrome or not is as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
void palindrome(int num) {
   int rev=0,val;
   val = num;
   while(num > 0) {
      rev = rev * 10 + num % 10;
      num = num / 10;
   }
   if(val==rev)
   cout<<val<<" is a palindrome"<<endl;
   else
   cout<<val<<" is not a palindrome"<<endl;
}
int main() {
   palindrome(12321);
   palindrome(1234);
   return 0;
}

Output

12321 is a palindrome
1234 is not a palindrome

In the above program, the function palindrome finds out if the number is palindrome or not. The function takes one parameter i.e num. Before any process takes place, a duplicate of num is made i.e val. The value of num is reversed and stored in rev.

This is shown by the following code snippet −

int rev=0,val;
val = num;
while(num > 0) {
   rev = rev * 10 + num % 10;
   num = num / 10;
}

After this, the value of rev is compared to val and not num. This is because the value of num is 0 by now. If rev is equal to val, then the number is a palindrome and this is printed, else the number is not a palindrome.

This can be seen in the following code snippet.

if(val==rev)
cout<<val<<" is a palindrome"<<endl;
else
cout<<val<<" is not a palindrome"<<endl;
raja
Published on 27-Sep-2018 10:47:35
Advertisements