Writing a recursive function
Introduction
Recursive functions are sometimes hard to write because we are not use to thinking about problems recursively. However, there are two things you should do:
- state the base case (aka easy case). what argument values will lead to a solution so simple that you can simply return that value (or do a very simple calculation and return that value? 
- state the recursive case. if you are given something other than the base case how can you use the function itself to get to the base case 
- Recursion is about stating a problem in terms of itself. The solution to the current problem is consist of taking a small step and restating the problem. 
Example:  The factorial function.
Write a function that is given a single argument n and returns n!. n! = n*(n-1)*(n-2) ...2* 1. For example 4! = 4 * 3 * 2 * 1 , by definition, 0! is 1
How would you do it recursively?
Lets start with base case. What value of n is it easy to come up with the result of n!?
0 is easy.. by definition 0! is 1. 1 is also easy because 1! = 1
Thus, we can establish that any value 1 or less is a base case with result of 1.
Now, the recursive case... how can we state factorial in terms of itself?
Let's consider this example: 5! = 5* 4* 3* 2 * 1. but... we can restate this as 5! = 5 * (4*3*2*1) but ... 4*3*2*1 is just 4!. So, 5! = 5 * 4!. In general we can say that n! = n * (n-1)!. We can pretty apply this idea to our function.
unsigned int factorial(unsigned int n){
    unsigned int rc = 1 ;              //base case result
    if(n > 1)                 //if n > 1 we  have the recursive case
        rc= n * factorial(n-1);  //rc is n * (n-1)!
    }
    return rc;
}Last updated
