To check if a number is a palindrome or not in C++

In this tutorial, we learn about How to check if a number is a palindrome number or not in C++.
Before we start, let’s know about what is palindrome number or how can we say that this is a palindrome number?

Palindrome number is a number,if you read from right to left or from left to right it does not change, it remains the same, that means if you reverse any number, then that number must be equal to its original, if  reverse of the number is not equal to its original then it is not a palindrome number.

let’s see an example:     121
the reverse of 121 is also 121
this is a palindrome number.

let’s see another example also,    145
the reverse of 145 is 541
this is not a palindrome number.




How to Check palindrome number in C++

#include <iostream>
using namespace std;
int main()
{
     int a, num, b, temp = 0;
     cout << "Enter a number: ";
     cin >> num;
     a = num;
     do
     {
         b = num % 10;
         temp = (temp * 10) + b;
         num = num / 10;
     } while (num != 0);
     cout << " Reverse of the number is: " << temp << endl;
     if (a == temp)
         cout << " This is a palindrome number.";
     else
         cout << " this is not a palindrome number.";
    return 0;
}

 

In the above piece of code, iostream is used for input /output stream, int main() tells the compiler that function will return an integer value. in this code we use doWhile loop, you can also use For loop.
A number which is entered by the user is stored in the variable num.

b = num % 10;
  • it is used to separate the last digit of the number inside the do-while loop
if (a == temp)
  • it is used to check if the original number is equal to its reverse or not.

let’s see the output of the program:

Enter a number: 12321
Reverse of the number is: 12321
This is a palindrome number. 

Enter a number: 145625
 Reverse of the number is: 526541
 This is not a palindrome number.

Do let me know in the comments section if you have any doubts.

Also read:


Leave a Reply

Your email address will not be published. Required fields are marked *