C++ Program To Check a Given Number is Palindrome or Not

A number that remains same when its digit are reversed is called a Palindrome Number.

Let’s Try to understand by Some Examples –

// Example 1
Input = 123
Reverse = 321
It is Not a Palindrome Number.
// Example 2
Input = 121
Reverse = 121
It is a Palindrome Number

How to execute this Program.

  • Define Variables “num”, “temp”, “digit”, “reverse”.
 int num,temp,r,rev=0;
  • Take Input from User.
cout<<"Enter the Number=";    
  • Store the given input in the variable “temp” and also save in another variable “num” to check with reversed number.
cin>>temp;    
num=temp;  
  • Reverse the Number using while() Loop.
 while(temp>0)    
    {    
      r=temp%10;    
      rev=(rev*10)+r;    
      temp=temp/10;    
    }   
  • Check if reversed number is same as the original number using if() Statement and give output according to that.
if(num==rev)    
      cout<<"Given Number is Palindrome.";    
    else    
      cout<<"Given Number is not Palindrome.";  

Code : To Check Palindrome Number

#include <iostream>  
using namespace std;  
int main()  
{  
     int num,temp,r,rev=0;
     cout<<"Enter the Number=";    
     cin>>temp;    
     num=temp;  

     while(temp>0)    
    {    
      r=temp%10;    
      rev=(rev*10)+r;    
      temp=temp/10;    
    }    

    if(num==rev)    
      cout<<"Given Number is Palindrome.";    
    else    
      cout<<"Given Number is not Palindrome.";   

  return 0;  
}  

Output

This image has an empty alt attribute; its file name is image-2.png

Logic

 while(temp>0)    
    {    
      r=temp%10;    
      rev=(rev*10)+r;    
      temp=temp/10;    
    }    

Leave a Reply