In this post, you will learn how to Check Whether a Number is Palindrome or Not using C++ programming language.
This lesson will teach you how to check whether a number is Palindrome or Not, with a do-while loop, assignment operator, decision making statement and mathematical functions using the C++ Language. Let’s look at the below source code.
How to Check Whether a Number is Palindrome or Not?
RUN CODE SNIPPETSource Code
#include <iostream> using namespace std; int main() { int n, num, digit, rev = 0; cin >> num; cout << "Enter a positive number: "<<num<<endl; n = num; do { digit = num % 10; rev = (rev * 10) + digit; num = num / 10; } while (num != 0); cout << "The reverse of the number is: " << rev << endl; if (n == rev) cout << "\nThe number is a palindrome."; else cout << "\nThe number is not a palindrome."; return 0; }
Input
12321
Output
Enter a positive number: 12321 The reverse of the number is: 12321 The number is a palindrome.
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function.
- A palindrome number is a number that is same after reverse. For example 121, 34543, 343, 131, 48984 are the palindrome numbers.
- Declare the variables n, num, digit, rev as variables and initialize the rev value as o.
- Collect the values from the user and store it in the integer values using function
cin>>
 and display the values usingcout<<
 and the Insertion Operators'<<‘ , ‘>>’. - Assign
n = num
using the assignment operator and create a do while loop with the condition where the value of n is not equal to 0. - In the do while loop the loop statement is executed once first and then the condition is verified. The loop is executed multiple times until the condition is not satisfied.
- In the loop statement first we find the reminder of num and 10 and store the value in digit, next we execute the mathematical expression
rev = (rev * 10) + digit
followed by the mathematical expressionnum = num / 10
- After the calculation the answer is displayed, then using the if else statement we declare the condition to compare the the initial number and the calculated number.
- According to the comparison, the respective output statement is displayed, whether the number is palindrome or not.
- The output statement is displayed and the execution is terminated.
Note: The ‘ << endl ‘ in the code is used to end the current line and move to the next line and ‘\n’ is also a new line function, to understand how both the functions work exclude it from the code, move it around and work with it.