interesting examples later in this book, recursion is useful. A recursive function is usually one that calls itself. It is similar to a loop with or without a
terminating condition. Some programming functions lend themselves to recursive algorithms, such as the factorial one. The factorial is a classic
recursive algorithm because it is very obvious. A simple mathematical definition of the factorial operation is:
Only registered users can see contents. Please click here to Register or Login.
Factorial is commonly represented by the exclamation mark (!).
With this algorithm, let’s calculate 3!:
1. fact(3) = 3 * fact(2)
2. fact(2) = 2 * fact(1)
3. fact(1) = 1 * fact(0)
4. fact(0) = 1
As you can see, the algorithm works its way down from the given number to zero, so when it gets to fact(0) it must work its way back up to the
We know that fact(0) = 1.
fact(1) = 1 * fact(0) = 1 * 1 = 1
fact(2) = 2 * fact(1) = 2 * 1 = 2
fact(3) = 3 * fact(2) = 3 * 2 = 6