Search code examples
c++recursionpalindrome

Check Palindrome using recursion


I am trying to implement a function that will check to see if a word is a palindrome Below is the code that i have tried to use. the code works for one letter words obviously and words that don't start and end with the same letter. It fails on anything else. Please help

bool is_palindrome(int start, int end, const string & str)
{
    if (str[start] != str[end])
        return false;
    else if (start == end)
        return true;
    else
        return is_palindrome(start++, end--, str);

    return false;
}

here is the main function that tis function calls http://csel.cs.colorado.edu/%7Eekwhite/CSCI2270Fall2011/recursion_lab/palindrome.cxx


Solution

  • start++ increments the [local] variable start, and evaluates to the old value. You want to evaluate to the new value, and you don't need to alter the local variable at all.

    So write start+1, end-1 instead, and then consider the case where your string has an even number of characters because there is another issue there.