Brief
Defining Recursion
In general, recursion is defined as the repeated application of a recursive procedure. In computer science, it is a programming technique involving the use of a function that calls itself one or more times until a specific condition is met (commonly known as the base case). Concretely, it is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem.
Prototyping
A recursive function has one or more base cases and one or more recursive calls.
A recursive call is a portion of the function that calls itself in order to get closer to solving the problem.
A base case is a condition which, if met, will cease further recursive calls.
The following pseudocode represents a typical format for a recursive function:
Factorial
A factorial is the product of an integer and all the integers below it. For example, factorial for 4 (denoted as 4!) is equal to 4*3*2*1 = 24. The code below is a recursive function definition for calculating a factorial.
If one were to make the function call factorial(4)
, the function would execute like the following:
- First it calculates
factorial(4)
. Sincen
= 4, the recursive case is true. Therefore factorial(4) equals4 * factorial(3)
. But now it needs to calculatefactorial(3)
to finish the problem. - It then calculates
factorial(3)
. Sincen
= 3, the recursive case is true. Therefore factorial(3) equals3 * factorial(2)
. But now it needs to calculatefactorial(2)
to finish the problem. factorial(2)
is then calculated. Sincen
= 2, the recursive case is true. Therefore factorial(2) equals2 * factorial(1)
. But now it needs to calculatefactorial(1)
to finish the problem.- Finally, it calculates
factorial(1)
. Sincen
= 1, the base case is true. Therefore factorial(1) equals1
. We’ve reached an endpoint and are now able to calculatefactorial(2)
completely to finish the problem. - Since the value of
factorial(1)
is 1, the calculation in step 3 forfactorial(2)
can finish.factorial(2)
= 2*1 = 2. - Now that it knows that the value of
factorial(2)
is 2, the calculation in step 2 forfactorial(3)
can finish.factorial(3)
= 3*2 = 6 - And finally, since
factorial(3)
is 6, the calculation in step 1 forfactorial(4)
can finish.factorial(4)
= 4*6 = 24.
Fibonacci
Another popular function is the recursive fibonacci. The Fibonacci series is a series of numbers in which each number is the sum of the two preceding numbers. Ex. 1, 1, 2, 3, 5, 8, etc. The fourth fibonacci number in this series if 3.
The code below is a recursive function definition for calculating the nth fibonacci number.
Walk through the each line of code and see why it works.
- Previous
- Next