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
Show 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.