APS105 Textbook 11.3 - Recursion in Arrays
You can use recursion to solve problems with arrays and strings.
Example: Use Recursion to Find if a String is a Palindrome
We can do this by comparing the first and last characters of a string, and then the second and second-last characters, and so on. This can be done recursively until you reach the middle of the string.
- Recursive step: compare
and character in string, then, if they are the same character, call the function again but with . - Base step: if you have reached the middle, do one final check and return True or False
- If
then you have reached the middle of an even-numbered string, so check the and term to see if they are the same; if they are, then return True. - If
then you have the reached the precursor to the middle of an odd-numbered string, so check if the and terms are the same. If they are, then return True.
- If
Code
#include <stdio.h>
#include <stdbool.h>
bool palindrome(char *s, int n, int length) {
if (n * 2 == length) {
// base case for even numbered string
if (s[n] == s[length - n - 1]) {
return true;
} else {
return false;
}
} else if (n * 2 + 1 == length) {
// base case for odd numbered string
if (s[n] == s[length - n - 1]) {
return true;
} else {
return false;
}
} else {
// recursive step
if (s[n] == s[length - n - 1]) {
return palindrome(s, n + 1, length);
} else {
return false;
}
}
}
int main(void) {
printf("isPalindrome(\"racecar\") = %d\n", palindrome("racecar", 0, 7));
printf("isPalindrome(\"e\") = %d\n", palindrome("e", 0, 1));
printf("isPalindrome(\"\") = %d\n", palindrome("", 0, 0));
printf("isPalindrome(\"race\") = %d\n", palindrome("race", 0, 4));
return 0;
}