page 2 of 3

The mathematical combinations operation is a good example of a function
that can quickly be implemented as a binary recursive function. The number
of combinations, often represented as
*nCk*
where we are choosing n
elements out of a set of k elements, can be implemented as follows:

int choose(int n, int k) { if (k == 0 || n == k) return(1); else return(choose(n-1,k) + choose(n-1,k-1)); }

An exponential recursive function is one that, if you were to draw out a
representation of all the function calls, would have an exponential
number of calls in relation to the size of the data set (exponential
meaning if there were
*n*
elements, there would be
*O*(*a*
^{n})
function
calls where a is a positive number).

A good example an exponentially recursive function is a function to compute
all the permutations of a data set. Let's write a function to take an
array of `n` integers and print out every permutation of it.

void print_array(int arr[], int n) { int i; for(i=0; i<n; i) printf("%d ", arr[i]); printf("\n"); } void print_permutations(int arr[], int n, int i) { int j, swap; print_array(arr, n); for(j=i+1; j<n; j) { swap = arr[i]; arr[i] = arr[j]; arr[j] = swap; print_permutations(arr, n, i+1); swap = arr[i]; arr[i] = arr[j]; arr[j] = swap; } }

To run this function on an array `arr` of length `n`, we'd do
`print_permutations(arr, n, 0)` where the `0 tells it to start
at the beginning of the array.
`

In nested recursion, one of the arguments to the recursive function is
the recursive function itself! These functions tend to grow extremely fast.
A good example is the classic mathematical function, "Ackerman's function.
It grows very quickly (even for small values of x and y, Ackermann(x,y) is
extremely large) and it cannot be computed with only definite iteration
(a completely defined `for()` loop for example); it requires indefinite
iteration (recursion, for example).

Ackerman's function int ackerman(int m, int n) { if (m == 0) return(n+1); else if (n == 0) return(ackerman(m-1,1)); else return(ackerman(m-1,ackerman(m,n-1))); }

Try computing ackerman(4,2) by hand... have fun!

Take a Study Break!