If you are familiar with programming, then you are probably familiar with the concept of functions. They are an important part of programming and they let us perform actions based on certain criteria. We can call the function as and when required. In addition to this, functions allow code reusability. We can write the logic for some particular task once inside a function and then later call whenever we are required to perform the task.
One very important type of function is the recursive function. It is a very important concept and has many uses. This concept is often confusing. In this post, I will describe recursive function in easy language and also explain with the help of an example program to make you grasp the concept well. So let’s get started.
We can define a recursive function as a function which calls itself. We know that we can call some particular function inside of some another function. For example:
Here, we are calling speak function from inside of talent function. This is a common practice. In case of recursive function, the function calls itself. That means, we call the same function frow within a function.
We need to be careful while writing recursive functions. We must write the logic in such a way that the execution stops after reaching a certain condition, otherwise the program will crash.
To make this clear, we will take the help of a program which calculates the factorial of a number. A factorial of a number n is denoted by n!=n(n-1)*(n-2)*(n-3)……….*1;
Lets now see the program.
Let us now understand this program.
The main function takes the input from the user to find the factorial of. After getting the number, it is passed to the findFactorial function as a parameter. The result is assigned to a long variable factorial which is later used to print the result.
Now the most important part is the logic of the findFactorial function.
- The findFactorial function takes an integer parameter a.
- Using if-else statement, it checks whether the value of a is 0. If it is 0, it returns 1 because 0!=1.
- If this is not the case, it returns a multiplied by result of the same findFactorial function, this time, the parameter is one less than a. Let us consider a to be 5. Then step 3 will produce the result 5*4.
- This process continues and the result goes on like 5*4*3*2*1. When the value of a reaches 0, then because of the if condition, it returns 1 and no more findFactorial function is called. The final result is 5*4*3*2*1 i.e. 120.
- The result 120 is passed to the factorial variable in the main method which is then displayed to the user using the printf statement.
You can see here that the function findFactorial is being called from inside the findFactorial function itself. This is a recursive function. And the if else condition provides a way to break the calling after a certain condition is met.
I hope you understood the concept of recursive function. Thanks for reading. Keep visiting iCuriousGeek.