Palindrome Checker in C++
This C++ program checks if a given number is a palindrome. A palindrome is a number that reads the same backward as forward. For example, 121 and 12321 are palindromes, but 123 is not.
Program Structure
The program follows these steps:
- Take an integer input from the user.
- Reverse the integer.
- Compare the reversed integer with the original integer.
- If they are the same, the number is a palindrome; otherwise, it is not.
C++ Code
// Including necessary libraries
#include <iostream> // for standard I/O operations
// Using the standard namespace
using namespace std;
/**
* Function to check if a number is a palindrome.
* @param num The integer to check.
* @return True if the number is a palindrome, false otherwise.
*/
bool isPalindrome(int num) {
int originalNum = num; // Store the original number
int reversedNum = 0; // To store the reversed number
int remainder; // To store the remainder during the reversal process
// Reverse the number
while (num != 0) {
remainder = num % 10; // Get the last digit
reversedNum = reversedNum * 10 + remainder; // Build the reversed number
num /= 10; // Remove the last digit
}
// Check if the reversed number is the same as the original number
return originalNum == reversedNum;
}
/**
* Main function.
*/
int main() {
int number; // Variable to store user input
// Prompt user for input
cout << "Enter an integer: ";
cin >> number;
// Check if the number is a palindrome and display the result
if (isPalindrome(number)) {
cout << number << " is a palindrome." << endl;
} else {
cout << number << " is not a palindrome." << endl;
}
return 0; // Indicate that the program ended successfully
}
Explanation
Libraries: The program includes the <iostream>
library for input and output operations.
Namespace: The using namespace std;
statement allows us to use standard library functions and objects without the std::
prefix.
isPalindrome Function: This function takes an integer as an argument and checks if it is a palindrome. It reverses the number by extracting each digit and reconstructing the number in reverse order. Finally, it compares the reversed number with the original number and returns true
if they are the same, and false
otherwise.
Main Function: The main function prompts the user to enter an integer, calls the isPalindrome
function, and then displays whether the number is a palindrome based on the function’s result.