C++ Program to Check for Palindrome

1. Introduction

A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Palindromic patterns are a recurrent theme in the world of problem-solving and often serve as an introductory challenge for algorithm enthusiasts. In this post, we will learn how to write a C++ program that checks if a given number is a palindrome.

2. Program Overview

The program will execute the following steps:

1. Prompt the user to input a number.

2. Reverse the entered number.

3. Compare the reversed number with the original. If they match, it's a palindrome; otherwise, it's not.

4. Display the result to the user.

3. Code Program

#include <iostream>
using namespace std;

int main() {
    int num, reverseNum = 0, remainder, originalNum;

    // Getting user input
    cout << "Enter an integer: ";
    cin >> num;

    originalNum = num; // Storing original number

    // Reversing the number
    while (num != 0) {
        remainder = num % 10;
        reverseNum = reverseNum * 10 + remainder;
        num /= 10;
    }

    // Checking for palindrome
    if (originalNum == reverseNum)
        cout << originalNum << " is a palindrome.";
    else
        cout << originalNum << " is not a palindrome.";

    return 0; // Signify successful program termination
}

Output:

Enter an integer: 121
121 is a palindrome.

4. Step By Step Explanation

1. Headers and Namespace: We start by incorporating the iostream library and designating the use of the standard namespace.

2. Main Function: The execution begins here. We declare our necessary variables: num to hold the original number, reverseNum for the reversed version, remainder for the modulus operation, and originalNum to store the original input.

3. User Input: The program uses cout to ask for user input and cin to fetch the number.

4. Reversing Logic: Using a while loop, we reverse the digits of the entered number.

5. Palindrome Check: Once reversed, we compare the originalNum with reverseNum. If they are identical, the number is palindromic.

6. Displaying the Result: Based on our comparison, a corresponding message is shown to the user.

7. Program Termination: The program concludes its execution and indicates success with a return value of 0.

Comments