We have seen the role of user defined functions earlier. The main reason why we use a function is because of its re-usability. We can call the same function again and again rather than writing the same piece of code multiple times. Today we will learn about recursive functions. A recursive function is a function that calls itself. As a fun fact, it is similar to the title of the Bollywood movie “Karthik calling Karthik” ( just for you to remember what a recursive function is !!)
Recursion is used to find the factorial of a number, to find fibonacci series terms ,etc on a basic level. Let us see how to use recursion for finding the factorial of a number.
What is factorial of n? Factorial of n is given by n!=n*(n-1)*(n-2)*…….1
Factorial of 8 is 8!=8*7*6*5*4*3*2*1= 40320
Factorial of 5 is 5!=5*4*3*2*1=120
In the definition of n! , n! = n*(n-1)*(n-2)*…….1
which is same as n*(n-1)!
I will simplify this concept with an example,
let us take the number 5 itself. Factorial of 5 is 5!=120
This is also equal to = 5*4! ; where 4! = 4*3*2*1
Let us find the factorial of a number using a recursive function.
In the above screenshot, we have defined a function called factorial which accepts a parameter n. Now the important thing about recursive functions is that if a particular condition is not met, the recursive function keeps calling itself and it can go on infinitely or end up in an error. So here, recursion happens till n is equal to 1. When n=1 , it stops the recursion by just returning 1 and not again calling the function. This is because 1 is the last number multiplied to every factorial. Till n=1, factorial function returns n*factorial of n-1 .
Let us see a few outputs.