Search code examples
c++recursionpalindrome

Finding a String Palindrome with a recursive function


I am trying to write a recursive function that will determine if a string is a palindrome. Here is what I have so far:

int main()
{
    string word = "madam";

    if (palindrome(word) == true)
        cout << "word is a palindrome!" << endl;
    else
        cout << "word is not a palindrome..." << endl;

    return 0;
}

bool palindrome(string word)
{
    int length = word.length();

    string first = word.substr(0,1);
    string last = word.substr((length - 1), 1);

    if (first == last)
    {
        word = word.substr((0 + 1), (length - 2));
        cout << word << " " << word.length() << endl;  // DEBUGGING
        if (word.length() <= 1) return true;  // Problem line?
        palindrome(word);
    }
    else
        return false;
}

For some reason when the recursive function gets deep enough, and word.length() is less than or equal to 1, It doesn't return true. I can't seem to figure out why. Is it something to do with how recursive functions work, or how I am readjusting the length of word in the line before I commented DEBUGGING?

I am not as talented at C++ as I should be, so please excuse me if my programming seems poor.


Solution

  • You are at least missing a return statement here:

        if (word.length() <= 1) return true;  // Problem line?
        return palindrome(word);    // ###### HERE !
    }
    else
        return false;
    

    If the length is not 1 you are calling recursively the palindrome function, ignoring its return value and then returning always false. With my fix, you will return the result of the palindrome function called with word after removing the first and last letter.