I need help with palindrome function plzzzz

Hello,

I’m currently stuck on the palindrome function exercises. I believe my code is correct but I might be wrong. Every time I try to run the code it just keeps coming back with an error on Codecademy. The question is, is my code correct because it does reverse the string but when it comes to checking the condition the output is always false.

#include <iostream>

// Define is_palindrome() here:
bool is_palindrome(std::string text){
  std::string reversed_text;

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

  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 it? Have you tried printing reversed_text to see for yourself? Printing is one way we can observe what our code is doing.

Yeah so when I change the return type on the function to void and printed reversed_text it does return the text reversed which is strange.

never mind it works now! some reason it worked on a text editor but not on the Codecademy editor haha. Last question its related to the code. When we’ve got the for loop, if we are reading the string backwards why do we have the " - 1"? would it not work without, the loop knows the size of the string so if we using “madam” as an example, we know the last element is 4 and we just counting back to 0. Kinda confusing

The code you posted won’t return anything. It has an infinite loop. The code in the loop doesn’t reverse the original text either. Is the code you are running different from what you posted.

I’ve tried to rewrite it in sublime and it worked on there, maybe I did do something different then. This is what I’ve done this time

#include
#include

void is_palindrome(std::string text){

std::string reversed_string = "";

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

std::cout << text << " : " << text.size() << "\n";
std::cout << reversed_string << " : " << reversed_string.size() << "\n";
std::cout << std::endl;
if(reversed_string == text){
	std::cout << "True!\n";
} else {
	std::cout << "False!\n";
}

}

int main(){
is_palindrome(“damian”);
is_palindrome(“josh”);
is_palindrome(“hannah”);
}

just to test it I included the cout for both strings and see their sizes but it does work now its really weird haha.

Your new code is significantly different from what you originally posted. Looks good. Nice job figuring it out.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.