Examples of Recursion


Problems

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


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.


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?


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


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.


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.


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


Take a Study Break

Green YOUR SCHOOL!

Click here to get involved with dosomething.org!

John Krasinski's BIG MIRACLE

Click to watch the trailer and read exclusive star interviews!

Do you like Anna?

Read Dear Albert... from ANNA's perspective!

BATTLESHIP, the movie

Here's why we're super jazzed about it.

Do energy juices actually work?

Our blogger puts 'em to the test!


The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps