C++ Program to Check Palindrome Number
A palindrome number is a number that is the same when read forward and backward. For example, 121, 323, 4554 are palindrome numbers. In this program, we will write a C++ code to check whether a given number is a palindrome or not.
Syntax
#include <iostream>
using namespace std;
int main() {
int num, reversed_num = 0, original_num, remainder;
// take input
cout << "Enter a positive integer: ";
cin >> num;
// copy the input
original_num = num;
// reverse the original number
while (num != 0) {
remainder = num % 10;
reversed_num = reversed_num * 10 + remainder;
num /= 10;
}
// check if the original and reversed numbers are the same
if (original_num == reversed_num) {
cout << original_num << " is a palindrome number";
} else {
cout << original_num << " is not a palindrome number";
}
return 0;
}
Example
Enter a positive integer: 121
121 is a palindrome number
Explanation
In the above example, we take an input number from the user and copy it to another variable called original_num. Then, we use a while loop to reverse the original number and store it in a variable called reversed_num. Finally, we check if the original and reversed numbers are the same and output the result.
Use
This program can be used to check whether a given number is a palindrome or not. It can be used in any scenario where you need to check if a number is the same when read forward and backward.
Important Points
- A palindrome number is a number that is the same when read forward and backward.
- To check if a number is a palindrome, reverse the original number and check if it is the same as the original number.
- The % operator gives us the remainder when one number is divided by another. This is used to get the last digit of a number.
- The /= operator is a shorthand operator that divides a variable by a given number and assigns the result to the same variable.
Summary
In summary, this C++ program checks whether a given number is a palindrome and outputs the result. It demonstrates the use of variables, loops, and conditional statements in C++.