• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Weird recursive return value

I'm taking a prereq CS class for my major, and one of the labs involves writing a recursive function that determines if a word is a palindrome or not. Easy. The function works fine (as proven by debugging text), but for some reason the return values are messed up (presumably by the recursion).

Here's the function code (C++, minus the debugging text)

bool isAPalindrome(char word[], int frontCursor, int backCursor)
{
if(word[frontCursor] == word[backCursor])
isAPalindrome(word, frontCursor + 1, backCursor - 1);
else if(frontCursor == backCursor)
return true;
else
return false;
}

For some reason, it returns some weird number if more than one recursive cycle is required (ie: 244). Any ideas?
 
There are several things wrong.
You don't have a return statement for the recursive case.
When you write recursive functions, you usually check the base cases first; you've got it backwards.. try tracing the function calls on paper for some input (e.g. ababa, abaaba, abaca), you should see what you're doing wrong pretty quickly.
 
In addition to statik213's observations, your code also fails for even-length words -- the two cursors pass each other and your termination condition is never reached.
 
Back
Top