Skip over navigation

Examples of Recursion

Problems

Recursion with the String Library

Recursion in Searching

Problem : Write the reverse() function recursively. This function takes a string and the length of the string as arguments and returns the same string with its characters in the reverse order.


void reverse(char *s, int len)
{
	char temp;
	if (len > 1) {
		temp = s[0];
		s[0] = s[len-1];
		s[len-1] = temp;
		reverse(s+1,len-2);
	}
}

Problem : Challenge: You're given a piece of memory containing characters divided into two sections, section a and section b, that follow each other in memory, b after a. You are also supplied with the lengths of a and b. Write a function that uses your reverse() function from above to swap the two sections such that the a section follows the b section. This does not require recursion.


void reverse_mem(char *s, int len_a, int len_b)
{
	reverse(s, len_a);
	reverse(s+len_a, len_b);
	reverse(s, len_a + len_b);
}

Problem : Write a function count_spaces(char *s) that counts the number of whitespace characters that appear in a string. Characters are whitespace as defined by the isspace() function in the ctype library. Write this function recursively.


void count_spaces(char *s)
{
	if (*s=='\0') return 0;
	else return ((isspace(*s) ? 1 : 0) + count_spaces(s+1));
}

Problem : Why would a programmer most likely not use recursion for an implementation of the string library?

As the coding and understanding complexity of the functions are similar in both the recursive and iterative versions, a programmer would likely choose to use iteration as it would require fewer system resources, such as memory on the call stack.

Problem : Write the function strrchr() iteratively and recursively.

Iteratively:

char *strrchr_i(char *s, char c)
{
	char *save;
	for(; *s!='\0'; s++) if (*s==c) save=s; 
	return (*save==c ? save : NULL);
}
Recursively:

char *strrchar_r(char *s, char c)
{
	char *save=NULL;
	if (*s != '\0') save = strrchr_r(s+1,c);
	if (save!=NULL) return save;
	else return (*s==c ? s : NULL);
}

Problem : A palindrome is a sequence of characters or numbers that looks the same forwards and backwards. For example, "Madam, I'm Adam" is a palindrome because it is spelled the same reading it from front to back as from back to front. The number 12321 is a numerical palindrome. Write a function that takes a string and its length as arguments and recursively determines whether the string is a palindrome: int ispalindrome(char *s, int len);


int ispalindrome(char *s, int len)
{
	if (len <=1 ) return 1;
	else return((s[0] == s[len-1]) && ispalindrome(s+1, len-2));
}

Problem : Write a recursive function void replace(char *s, char from, char to); that changes all occurrences of from in s to to. For example, if s were "steve", and from == 'e' and to == 'a', s would become "stava".


void replace(char *s, char from, char to)
{
	if (*s != '\0') {
		if (*s == from) *s = to;
		replace(s+1, from, to);
	}
}

Follow Us