Yu Sasaki's Blog

Icon

プログラミングとか英語とかの練習!

Palindrome example using recursion in C

Today I tried resolving a problem with the palindrome example.

Here’s my code:

#include<stdio.h>
#include<string.h>

int do_palindrome(char *str, int offset){
	int ok = 1;
	int length = strlen(str);

	if(length/2 > 0)
		ok = (str[0] == str[length - 1 - offset])?
				do_palindrome(++str, ++offset):0;

	return ok;
}
int main(){
	int i = 0;
	int ok = 0;
	char* str[] = {"sasaki", "SOS", "12344321", "1234322",
                                             "555", "0", "ikki"};

	for(i=0 ; i<7 ; i++){
		ok = do_palindrome(str[i], 0);
		printf("%s is palindrome? : %d\n", str[i], ok);
	}

	printf("Finished!");
	return 0;

}

sasaki is palindrome? : 0
SOS is palindrome? : 1
12344321 is palindrome? : 1
1234322 is palindrome? : 0
555 is palindrome? : 1
0 is palindrome? : 1
ikki is palindrome? : 1
Finished!

According to Danny, our professor for DSA555, the keys to create a recursive function are the following:

1. Determine the base case

2. Make a progress toward the base.

If we apply the rule to our example above, the 1st rule is for “length/2 > 0.” The 2nd rule is how we make a progress toward the condition of “length/2 > 0.” Each time the function is recurred, we have to make sure the 1st, 2nd, 3rd… character is always compared with the last nth, n-1th, n-2th,… character at a time so that both sides get decreased in order to be closed to the center point.

This would be really hard if I do not know the rule.
I like abiding by a rule.

See you!

Advertisements

Filed under: DSA555