# What is Recursion?

### Contents

#### 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?

This function returns the result of multiplying two positive integers. It is a linear recursive function (it only makes one call to itself). Some might also consider it tail recursion, although technically the last thing it does is add a to the result of the function call, so it isn't really.

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?

This function is linearly recursive, and is tail recursive. The last thing it does if it makes a recursive call is to make the recursive call.

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

```
int pow(int a, int b)
{
int i, total=1;
for(i=0; i<b; i++) total *= a;
}
```

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

It is a binary recursive function. There will be 1023 function calls (including the initial call func(10)).

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

There will be 310 - 1 function calls.