Search code examples
c++recursionpalindrome

Palindrome function using recursion


I cant see where i've gone wrong here , its working for some palindromes but not working for others.

Basically the program takes in a word , the length of the word and then returns if it is a palindrome or is not a palindrome , and the function must use recursion.

bool palindrome(char a[],int length){
 int start = *a;
 if (*a != a[length-1])
    return false;

 if (*a == a[length-1]||start<length)
    return true;

 else 
    return palindrome(a+1,length-1);

 return false;
}

Can anyone see any problems with this function?


Solution

  • My duck says you are very close. He says you need to forget about whatever you were trying to do with start and that each recursion reduces length by 2, not 1 (because the first character is paired with its match, the last character). Then he showed me this:

    bool palindrome(const char* a, int length) {
        if(length < 2) return true;
        if(a[0] != a[length-1]) return false;
        return palindrome(a+1, length - 2);
    }