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

Algorithm:-

  1. Take integer number as input and store it in num
  2. store copy of num in temp
  3. we have to extract the digits of number using Modulus % operator
  4. reverse intialized to 0
  5. A  do while loop is started
    • unit digit is extracted and stored in rem

                       rem=num%10;

    •  We have to shift the reverse to left by multiplying by 10 and add remainder to it

                       reverse=reverse*10+rem; 

    • 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);

      5. reverse is printed as output as it is the reverse of the number entered by the user.

      6.  if  temp==reverse print number is palindrome otherwise number is not palindrome

C++ Code:-

    
    //C++ Program
    //Palindrome or not
    #include <iostream>
    using namespace std;
    //main Program
    int main()
    {
        int numdigitreverse = 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.