SparkNotes Shopping Cart  |     |  Checkout
Brought to you by Barnes and Noble
What is Recursion?
 
 
Problems
Problem 2.1: What does the following function do?
int mystery(int a, int b) 
{
	if (b==1) return a; 
	else return a + mystery(a, b-1); 
}
How would you categorize it? [Solution]
Problem 2.2: Suppose we wrote a function to see if a tree node is part of a tree whose root has a specified name:
int root_named_x(tree_node_t *node, char* x)
{
	if (strcmp(node->name, x) == 0) return 1;
	else if (node->parent == NULL) return 0;
	else return root_named_x(node->parent, x);
}
How would you categorize this function? [Solution]
Problem 2.3: Convert the following tail-recursive function into an iterative function:
int pow(int a, int b)
{
	if (b==1) return a;
	else return a * pow(a, b-1);
}
[Solution]
Problem 2.4: What category would the following function fit into? How many function calls will there be in total if the function is called with func(10)?
void func(int n)
{
	if (n!=1) {
		func(n-1);
		func(n-1);
	}
}
[Solution]
Problem 2.5: Continuing from the last problem, with a call func(10), how many function calls will there be in total with the following function?
void func(int n)
{
	if (n!=1) {
		func(n-1);
		func(n-1);
		func(n-1);
	}
}
[Solution]
Help | Feedback | Make a request | Report an error | Send to a friend
 
Study right for the SAT II Chemistry test with the experts at SparkNotes.
More...
 
Beat the SAT II Biology test with the latest book from the experts at SparkNotes.
More...
 
 
Go to top