C++ program to check whether a number is Palindrome or not

Program to check whether a number is Palindrome or not

 

Here we will discuss how to check whether a number is palindrome or not using C++ Programming language.

A number is a Palindrome number if the reverse of the number and the numbers itself are equal i.e. if number and its reverse are same then the number is a palindrome number.

Example: Let’s take a number say 2876. Here the reverse of the number is 6782 which is not equal to the number so 2876 is not a palindrome number. 

Let’s take another number say 12121. Here the reverse of the number is 12121 which is equal to the number, so 12121 is a Palindrome number.To check for palindrome number we will first reverse the number using a loop and then compare them number and its reverse using the if statement.

Program to check whether a number is Palindrome or not

Working

Let’s see how the code works:

  • User gives an input.
  • Input is stored in an int type variable say num.
  • num is copied in another int type variable temp
  • Now using a do while loop the reverse of num will be found.
    • Modulus(%) of num is found with 10 and stored in an int type variable say digit.

digit = num%10;

    •  An int variable reverse(initialised at 0) is multiplied by 10 and digit is added to it and the result is stored in reverse itself.

reverse = (reverse*10) + digit; 

    • num is divided by 10 and the value is stored in num itself.

        num /= 10;

    • The loop works until num is not equal to 0.

while(num!=0);

  • Now reverse will be compared with temp.
  • If both are equal then the num is Palindrome
  • Otherwise the num is not a Palindrome.

C++ Code

//C++ Program
//Palindrome or not
#include <iostream>
using namespace std;
//main Program
int main()
{
int num, digit, reverse = 0;
cout << "Enter a positive integer: ";
//user input
cin >> num;
int temp = num;
//loop to find reverse
do
{
digit = num % 10;
reverse = (reverse * 10) + digit;
num = num / 10;
} while (num != 0);
cout << "The reverse of "<< temp <<" is "<< reverse << endl;
//checking for palindrome
if (temp == reverse)
cout << "The number is a palindrome.";
else
cout << "The number is not a palindrome.";
return 0;
}

Output

Enter a positive integer: 12121
The reverse of 12121 is 12121
The number is a palindrome.

Please Login/Signup to comment