Recursive Function - r - learn r - r programming
- A function that calls itself is called a recursive function and this technique is known as recursion.
- To solve this problems we break the programs into smaller and smaller sub-programs.
- Consider the example to find the factorial of a number.
- Factorial of a positive integer number is defined as the product of all the integers from 1 to that number.
- The factorial of 5 is denoted as 5!
- This solution for finding the factorial of 5 is broken down into a sub-problem by multiplying the factorial of 4 with 5.
- Or more generally,
- Continue this process until we reach 0! which is 1.
- Implementation for the factorial is specified in the below example
Example: Recursive Function in R
- Here the function which will call itself like recursive.factorial(x) will turn into x * recursive.factorial(x) until x becomes equal to 0.
- When x becomes 0, we return the value as 1 because the factorial of 0 is 1.
- This will be the ending condition. Without this the recursion will not end and continue undetermined.
- Some sample function calls to our function are given
- The use of recursion makes code shorter and looks clean.
- It expresses in a function that calls itself.
- Recursive functions are also memory intensive.
- It shorten the complex and nested code.