Recursion

Now that we are familiar with functions, let's have a review on the most important concept using a function: recursion.

What Is Recursion?

Recursion is when a ​function calls itself again and again until it reaches the base condition.

Parts of a Recursion

There are two parts of recursion: base condition and recursive function.

For instance, take the example of a Factorial function.

Factorial(!) of a number n is the product of all positive numbers from our chosen number n down to 1.

factorial(n) = 1   if n <= 1  #base case
                        
factorial (n) = n * factorial(n-1) #recursive function                      

Let’s use an example of factorial of 5.

5! = 5 × 4!
   = 5 × 4 × 3!
   = 5 × 4 × 3 ×2! 
   = 5 × 4 ×3 ×2 ×1
   = 120 

Below is the call to the function factorial given 5 as a parameter to the function. factorial(5)

It is calculated recursively in the following manner:

Get hands-on with 1400+ tech skills courses.