‹ Back to the paper
Question 57
2 marks
Computer ScienceISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024)Short answerRecursion
Answer the following question.
A student has written the following code. It is written to check whether a string is palindrome or…
A student has written the following code. It is written to check whether a string is palindrome or not. However, the code is not giving the desired result when the parameter “MADAM” is passed to the method isPalindrome(). Analyse the code and find out the logical error.
public class PalindromeTesting
{
public static boolean isPalindrome(String word)
{
if (word.length( ) < 1)
{
return true;
}
else if (word.charAt(0) != word.charAt(word.length( ) - 1))
{
return false;
}
else
{
return isPalindrome(word.substring(0, word.length( ) - 1));
}
}
}Answer
Answer
Logical error: in the recursive call isPalindrome(word.substring(0, word.length()-1)), only the last character is dropped; the first character (already compared) is not dropped. So the next comparison compares the original first character again, but against a different (wrong) last character, giving a wrong result (isPalindrome("MADAM") incorrectly returns false). The substring should drop both ends: it should be word.substring(1, word.length()-1).