Yu Sasaki's Blog



Palindrome example using recursion in C

Today I tried resolving a problem with the palindrome example.

Here’s my code:


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

	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

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!


Filed under: DSA555

One Response

  1. what if a user wanted to encode a string and we wants to determine weather the the string is Palindrome or not, how you gonna do that in C programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: