Skip over navigation

Examples of Recursion

Problems

Recursion on Numbers

Recursion with Trees

Problem : Write a function to recursively print out an integer in any base from base 2 to base 9.


void print_base(int num, int base)
{
	if (num / base) print_base(num / base, base);
	putchar(num % base + '0');
}

Problem : Write a recursive function int count_digit(int n, int digit); to count the number of digits in a number n (n > 0) that are equal to a specified digit. For example, if the digit we're searching for were 2 and the number we're searching were 220, the answer would be 2.


int count_digit(int n, int digit)
{
	int count;
	if (n == 0) return 0;

	if (n % 10 == digit) return 1 + count_digit(n / 10, digit);
	else return count_digit(n / 10, digit);
}

Problem : For some reason, the computer you're working on doesn't allow you to use the modulo operator % to compute the remainder of a division. Your friend proposes the following function to do it:


int remainder(int num, int den)
{
	if (num < den) return num;
	else return(remainder(num - den, den));
}
Does this function work? Is there a better way?

Yes, the function does work, however there is a much more efficient method to compute the remainder by taking advantage of integer division:

int remainder(int num, int den) {
	return num - (den * (num / den));
}

Problem : The following function iteratively computes x n :


int exponentiate_i(int x, int n)
{
	int i, result = 1;
	for(i=0; i<n; i++) result *= x;
	return result;
}
Write a function to do this recursively in O(n) time).


int exponentiate_r(int x, int n)
{
	if (n==0) return 1;
	else return x * exponentiate_r(x, n-1);
}

Problem : Use the knowledge that x n = = (x 2)( n/2) when n is even to write a more efficient solution to the above problem.

If n is even, then x n = = (x 2)( n/2) . If n is odd, then x n = = x*(x 2)((n - 1)/2) . So:

int exponentiate2_r(int x, int n)
{
	if (n==0) return 1;
	else if (n % 2==0) return exponentiate2_r(x*x, n/2);
	else return x * exponentiate2_r(x*x, (n-1) / 2);
}

Problem : The classic fibonacci problem, where the next term in the sequence is the sum of the previous two terms, is often called fib2. One could also imagine a sequence fibN, where N is the number of previous terms to sum up. Write this function recursively.


int fibN(int num, int terms)	/* terms is the N */
{
	int i, total = 0;
	if (num<=1) return 1;
	else {
		for(i=1; i <= terms; i++) total += fibN(num-i, terms);
		return(total);
	}
}
Note: This code does not handle error checking.

Problem : What operation does the following function implement when p is 0, 1, and 2?


int mystery(n, m, p)
{
	int i, result = 0;
	
	if (p==0) return n+m;
	for (i=0; i< m; i++) result += mystery(result,n,p-1);
	return result;
}

When p==0, this is an addition function. When p==1, this is a multiplication function. When p==2, this is a power function.

Follow Us