Write a C++ program that checks whether a given integer is a palindrome or not.
Input and Output Examples
- Input: 121
Output: 121 is a palindrome. - Input: 12321
Output: 12321 is a palindrome. - Input: 12345
Output: 12345 is not a palindrome.
Algorithm to check a given number is palindrome or not:
- Start the Program: Include necessary headers and declare the use of the standard namespace.
- Prompt for Input: Ask the user to enter an integer.
- Read the Input: Store the integer in a variable.
- Check for Palindrome: Use a method to determine whether the number is a palindrome.
- Display the Output: Print whether the number is a palindrome or not.
- End the Program: Finish execution cleanly.
C++ Programs with Different Methods to Check Palindrome
Method 1: Using Arithmetic Operations
This method involves using arithmetic operations to reverse the number and then comparing it with the original number.
#include <iostream>
using namespace std;
int main() {
int num, originalNum, reversedNum = 0, digit; // Declare variables for the input number, original number, reversed number, and digit.
cout << "Enter an integer: "; // Prompt the user for input.
cin >> num; // Read the input value.
originalNum = num; // Store the original number for comparison.
// Reverse the number using arithmetic operations
while (num != 0) {
digit = num % 10; // Extract the last digit of num.
reversedNum = reversedNum * 10 + digit; // Append the digit to reversedNum.
num /= 10; // Remove the last digit from num.
}
// Check if the original number is equal to the reversed number
if (originalNum == reversedNum) {
cout << originalNum << " is a palindrome." << endl; // Display if the number is a palindrome.
} else {
cout << originalNum << " is not a palindrome." << endl; // Display if the number is not a palindrome.
}
return 0; // End the program successfully.
}
Method 2: Using String Conversion
This method converts the number to a string and then compares the string with its reverse.
#include <iostream>
#include <string>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
string numStr = to_string(num); // Convert the integer to a string.
string reversedNumStr(numStr.rbegin(), numStr.rend()); // Reverse the string.
// Check if the original string is equal to the reversed string
if (numStr == reversedNumStr) {
cout << num << " is a palindrome." << endl; // Display if the number is a palindrome.
} else {
cout << num << " is not a palindrome." << endl; // Display if the number is not a palindrome.
}
return 0;
}
Practice Problem
Write a C++ program to check whether a given string is a palindrome or not, considering both alphabetic and numeric characters while ignoring case sensitivity.