What is Recursion?
Problems
Problem : 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?
Problem : 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?
Problem : 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);
}
Problem : 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);
}
}
Problem : 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);
}
}





