Palindrome Word Checker using String Manipulation

Check if a Word is a Palindrome in C++

In this exercise, you will write a program that checks whether a given word is a palindrome. A palindrome is a word that reads the same forwards and backwards, such as "radar" or "level".

This exercise is designed to improve your understanding of string manipulation and comparison in C++. You'll gain hands-on experience with std::string, loop structures, and logical conditions.

Logic Breakdown

Input Reading

The program prompts the user to enter a single word and stores it in a string variable.

Comparison Loop

Iterates through half the word, comparing the character at index i with the one at length - i - 1.

Boolean Result

A flag is used to determine if the criteria is met. If a mismatch is found, it exits the loop early.

Objectives

  • 1. Prompt the user to enter a word and determine its length.
  • 2. Check if the word reads the same forwards and backwards.
  • 3. Use a bool flag and a break statement for optimized logic.
  • 4. Display a clear message indicating the palindrome status.

Example C++ Code

palindrome_checker.cpp Strings & Loops
#include <iostream>
#include <string>

using namespace std;

int main() {
    string word;
    bool isPalindrome = true;

    cout << "Enter a word: ";
    cin >> word;

    int length = word.length();

    // Logic to compare characters from start and end
    for (int i = 0; i < length / 2; i++) {
        if (word[i] != word[length - i - 1]) {
            isPalindrome = false;
            break; // Exit if a mismatch is found
        }
    }

    if (isPalindrome) {
        cout << word << " is a palindrome." << endl;
    } else {
        cout << word << " is not a palindrome." << endl;
    }

    return 0;
}

Console Output:

Enter a word: radar
radar is a palindrome.
Keywords & Concepts
Mirror Logic String Indexing State Flags Break Statement
© C++ Programming Exercises. Master the art of performance coding.