Challenge: Palindrome
Completed
A palindrome reads the same forwards and backwards, like level or racecar. Read one word (small letters only) and print yes if it is a palindrome, otherwise no.
Input
One word.
Output
yes or no.
Example
Input
racecar
Output
yes
Editor
C++
Hints
Compare the first letter with the last, the second with the second-to-last, and so on.
The partner of index i is n - 1 - i.
Another way: copy the word, reverse the copy, and compare.
Solution explanation
Walk from both ends towards the middle. One mismatch is enough to say no.
Show solution
#include <iostream>
#include <string>
using namespace std;
int main() {
string word;
cin >> word;
bool same = true;
int n = word.length();
for (int i = 0; i < n / 2; i++) {
if (word[i] != word[n - 1 - i]) {
same = false;
}
}
cout << (same ? "yes" : "no") << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module