Check Palindrome Number C++ Program 

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.
Source Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
int main()
{
     int n, num, digit, rev = 0;
     cout << "Enter a positive number: ";
     cin >> num;
     n = num;
     do
     {
         digit = num % 10;
         rev = (rev * 10) + digit;
         num = num / 10;
     } while (num != 0);
     cout << " The reverse of the number is: " << rev << endl;
     if (n == rev)
         cout << " The number is a palindrome.";
     else
         cout << " The number is not a palindrome.";
    return 0;
}

Another Example

#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;

Post a Comment

 
Top