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.
  •  r recursion
  • 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!
5! = 1*2*3*4*5 = 120
  • This solution for finding the factorial of 5 is broken down into a sub-problem by multiplying the factorial of 4 with 5.
5! = 5*4!
  • Or more generally,
n! = n*(n-1)!
  • 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

# Recursive function to find factorial

recursive.factorial<- function(x) {
if (x == 0)    return (1)
elsereturn (x * recursive.factorial(x-1))
}
  • 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
>recursive.factorial(0)
[1] 1

>recursive.factorial(5)
[1] 120
>recursive.factorial(7)
[1] 5040
  • 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.


Related Searches to Recursive Function