In this blog, we will create a program to check whether a number is a palindrome or not using C++.
What is a Palindrome number?
If the reverse of a number is equal to the number itself, then it is called a palindrome number for example 121, 15751, etc.
Algorithm to check if a number is a palindrome or not.
- Get the input number from the user.
- Store it in a temporary variable.
- Turn the number.
- After reversing, compare to a temporary variable.
- If it is the same, then the number is a palindrome.
C++ code to check whether a number is palindrome or not
#include <iostream> using namespace std; int main() { int n,sum=0,temp,reverse; cout<<"Please enter the Number="; cin>>n; temp=n; while(n>0) { reverse=n%10; sum=(sum*10)+reverse; n=n/10; } if(temp==sum) cout<<"The number is Palindrome."; else cout<<"The number is not Palindrome."; return 0; }
Explanation of the code
The above code will take a number as an input from the user and put it into a temporary variable as you can see that sum is already 0 it will use a while loop until the number becomes 0 and as the code is written it will perform the operation as written after while loop. If the number becomes 0 then it will check if the temporary variable is equal to the sum or not. If the condition satisfies then it will print that the number is a palindrome otherwise if the condition fails it will go to else part and will print that the number is not a palindrome.
One more example using a do-while loop will also explain the algorithm we discussed in the introduction. We will take a number as an input from the user and check if it is a palindrome or not.
Output of the code