Exercise 20: Recursion

For this assignment you will write two recursive functions, one to calculate a factorial, and another to find the maximum value in an array.

Note that in C it is generally more efficient to perform these calculations using loops instead of using recursion. We are using recursion here to practice recursive problem solving, not to implement efficient solutions.

factorial()

There is already a prototype for this function in recursive_functions.h:

unsigned int factorial(unsigned int n);

Implement this function in recursive_functions.c, and uncomment the line in main.c that tests it so you can try it out.

The factorial of a positive integer n, or n!, is the product of the integers 1 through n. For example:

4 ! = 1 2 3 4 = 24


Since 0! is defined to have the value 1, we can define a factorial recursively like so:

n ! = { 1 if  n = 0 n ( n 1 ) ! otherwise


Note that this is very similar to the recursive definition of the nth triangle number Tn:

T n = { 0 if  n = 0 n + T n 1 otherwise


Thus the implementation of factorial() is going to be very similar to the implementation of triangle_number() from the in-class example code.

array_max()

There is already a prototype for this function in recursive_functions.h:

int array_max(int *array, size_t size);

Implement this function in recursive_functions.c, and uncomment the line in main.c that tests it so you can try it out.

When implementing array_max(), if there is only one value in the array, then the max is that value (this is the base case). Otherwise, compare the last value in the array to the max of the rest of the array (recursively), and return the larger value. Since you may need to use the result of the recursive call twice (once in the comparison and perhaps once in a return statement) it is a good idea to store the result of the recursive call to array_max() in a variable to avoid calling the function recursively twice.

Local Testing

You can run the GitHub testing locally with the command:

make gh-test-recursion

Submission

Push your submission to GitHub to run the automated testing. You must not use any loops in recursive_functions.c.

Grading

Your grade for this assignment will be out out of 10 points: