What is wrong with my palindrome function?

Hi,

I am a newcomer about C++ and I am stuck with the exercise for Palindrome function.
Below is my code:

bool is_palindrome(std::string text) {

std::string reversed_text = “”;

for (int i=0; text.size(); i++) {
reversed_text[i] = text[text.size()-i];
}

if (reversed_text == text ) {
return true;
}
else {
return false;
}
}

int main() {

std::cout << is_palindrome(“madam”) << “\n”;
std::cout << is_palindrome(“ada”) << “\n”;
std::cout << is_palindrome(“lovelace”) << “\n”;

}

Does anyone can tell me which part is wrong?
Thanks!

You have a few issues to address.
First, reversed_text is initialized to an empty string. In this statement reversed_text[i] = text[text.size()-i]; reversed_text[i] doesn’t exist. There is no position or index in an empty string. You can add the character to the empty string using the += operator.
Second, in the same statement reversed_text[i] = text[text.size()-i]; the expression text[text.size()-i] is not giving you what you want. The size() of “madam” is 5, but the last character “m” is not at index 5, it’s at index 4. Indexes start at 0. If you subtract 1 from the results of your current expression, you’ll get the proper index.
Third, for (int i=0; text.size(); i++) isn’t doing what you expect for the same reason as previously mentioned. text.size(); is the stop condition for your loop. The text.size() for “madam” is 5, but the indexes for the characters in “madam” are 0, 1, 2, 3, 4. You’ll want to continue iterating while i < text.size().

I’ve included your original code with the necessary changes below. Please try correcting your code before peeking :wink:

bool is_palindrome(std::string text) {
  std::string reversed_text = "";

  for (int i=0; i < text.size(); i++) {
    reversed_text += text[text.size() - 1 -i];
  }

  if (reversed_text == text ) {
    return true;
  }
  else {
    return false;
  }
}

int main() {

std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";

}

One last thing. Your method for reversing the text works, but the more orthodox method would be like this:

for (int i = text.size() -1; i >= 0; i--) { //start i at the end, and iterate backwards
  reversed_text += text[i];
}

Just food for thought. Your method works too.
Hope this helps! && Happy coding!

2 Likes

Hi,

Thanks a lot!
I understand what’s wrong with my coding now and have make some modification.:smile:

Thanks again and have a nice weekend!

1 Like