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.
Efficiency Tip: length / 2
We only need to loop until length / 2 because once we reach the center, all characters have already been compared with their opposites. This doubles the efficiency of the check.
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
boolflag and abreakstatement for optimized logic. - 4. Display a clear message indicating the palindrome status.
Example C++ Code
#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:
radar is a palindrome.