Date | November 2017 | Marks available | 5 | Reference code | 17N.2.HL.TZ0.19 |
Level | HL | Paper | 2 | Time zone | no time zone |
Command term | Describe | Question number | 19 | Adapted from | N/A |
Question
A palindrome is a word that spells the same backwards. For example, the words “kayak” and “rotor” are palindromes.
A word can be checked to see if it is a palindrome by comparing the first letter with the last letter and then the second letter with the next-to-last letter and so on.
Explain why recursion is a suitable tool to use when performing this check.
The method palindrome()
is called by boolean t = palindrome(word)
;
where word
is a String variable.
Without writing code, describe the recursive method palindrome()
that returns whether or not a word is a palindrome.
Markscheme
The solution repeats the same algorithm/series of steps/code;
With a changing/different parameter set;
Until a base/terminating case is reached;
Note: Do not award marks for “the method calls itself”.
The base case will return true if the length of word = 0 or 1 (must have both values) / The index of last character <= index of the first character;
Otherwise the first and last letters will be compared;
Returns false if they are not equal;
If they are equal, calls the method again;
With, as its parameter, the word stripped of its first and last letters (can use indices);