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.

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;
}