Home > SparkNotes > Computer Science Study Guides > What is Recursion? >

sparknotes

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.