What is Recursion?


Problems

Problem : Define "recursion". What does it mean for a function to be recursive?


Problem : Your boss asks you to write a function to sum up all of the numbers between some high and low value. You decide to write two different versions of the function, one recursive and one iterative. 1) Write them. The next morning you come into work and your boss calls you into his office, unhappy at how slow both of your functions work, compared to how the problem could be solved. 2) How else could you solve this problem?


Problem : What is a base case? Why must a recursive function have a base case? Can a function be written recursively if a base case is not known?


Problem : What is wrong with the following function?


int factorial(int n)
{
	if (n<=1) return 1;
	else if (n<0) return 0;
	else return factorial(n-1) * n;
}


Problem : Your research assistant has come to you with the following two functions:


int factorial_iter(int n)
{
	int fact=1; 
	if (n<0) return 0; 
	for( ; n>0; n--) fact *= n; 
	return(fact);
}
and

int factorial_recur(int n)
{
	if (n<0) return 0;
	else if (n<=1) return 1;
	else return n * factorial_recur(n-1);
}
He claims that the factorial_recur() function is more efficient because it has fewer local variables and thus uses less space. What do you tell him?


Problem : As you probably noticed, the size of n! grows quickly as n increases. As such, you will probably reach a point were your computer can no longer represent the value of n! (unless you are using language with a big number library or unlimited integer precision). Determine what the largest value of n is for which the computer can accurately compute n! .


Problem : Back to the problem of programming Data to walk. Write a function void walk(int n) that takes n steps. You should use the void take_one_step() function as a helper function.


Take a Study Break

SparkLife

What's your Pretty Little Liars name?

Take this quiz to find out!

SparkLife

Which young actress just got married?

Click to find out!

SparkLife

Cat bearding WINS THE INTERNET

Have you seen this yet?

SparkLife

Scary movies with funny posters

These. Are. Hilarious.

Geek out!

The MindHut

Geeky Actors: Then and Now

Travel back in time!

The MindHut

Villains We Want These Actresses to Play

From super cute to super bad!

The MindHut

10 Movies Better Than Their Books

What do you think?

The MindHut

Summer Movie Open Thread

Leave your thoughts here!

The MindHut

12 Scientific Inaccuracies in Into Darkness

What did Star Trek get wrong?

The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps