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". The program will prompt the user to enter a word, then analyze the characters from the beginning and end of the word towards the center to determine if it meets the criteria of a palindrome.

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

Group

Advanced Conditional Structures in C++

Objective

1. Prompt the user to enter a word.
2. Check if the word reads the same forwards and backwards.
3. Display a message indicating whether the word is a palindrome or not.

Write a program that checks whether a word is a palindrome.

Example C++ Exercise

 Copy C++ Code
#include <iostream>   // Include for input and output
#include <string>     // Include for using std::string

using namespace std;

int main() {
    string word;        // Variable to store the user's input
    bool isPalindrome = true;  // Boolean flag to determine if the word is a palindrome

    // Ask the user to enter a word
    cout << "Enter a word: ";
    cin >> word;  // Read the word from user input

    int length = word.length();  // Get the length of the word

    // Loop to compare characters from the beginning and end
    for (int i = 0; i < length / 2; i++) {
        if (word[i] != word[length - i - 1]) {  // Compare characters from opposite ends
            isPalindrome = false;  // If mismatch, set flag to false
            break;  // No need to continue if already not a palindrome
        }
    }

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

    return 0;  // End of program
}

 Output

Enter a word: radar
radar is a palindrome.

Share this C++ Exercise


More C++ Programming Exercises of Advanced Conditional Structures in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.