w3resource

Factorial calculation with Recursion in R

R Programming: Control Structure Exercise-8 with Solution

Write a R program to find the factorial of a given number using recursion.

Sample Solution :

R Programming Code :

# Define a function to calculate the factorial of a given number using recursion
factorial <- function(n) {
    if (n == 0) {  # Base case: Factorial of 0 is 1
        return(1)
    } else {
        # Recursive case: Calculate factorial using recursion
        return(n * factorial(n - 1))
    }
}

# Test the function with an example input
number <- 7  # Example number for which factorial is to be calculated
result <- factorial(number)

# Print the result
cat("The factorial of", number, "is:", result, "\n")

Output:

The factorial of 7 is: 5040               

Explatnaion:

In the exercise above,

  • The "factorial()" function takes one parameter 'n', which represents the number whose factorial is to be calculated.
  • It starts with a base case: if 'n' is 0, it returns 1 because the factorial of 0 is defined as 1.
  • If 'n' is greater than 0, it uses recursion to calculate the factorial by multiplying 'n' with the factorial of (n-1).
  • The function is then tested with an example input ('number'), and the result is printed to the console.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Fibonacci nth term with Recursion in R.
Next: Sum of Cubes calculation with For loop in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.