Calculate Factorial with Recursion & Iteration in R
Write a R program function to calculate the factorial of a given number using both recursion and iteration (for loop).
Sample Solution :
R Programming Code :
# Function to calculate factorial using recursion
factorial_recursion <- function(n) {
if (n == 0) {
return(1)
} else {
return(n * factorial_recursion(n - 1))
}
}
# Function to calculate factorial using iteration (for loop)
factorial_iteration <- function(n) {
result <- 1
for (i in 1:n) {
result <- result * i
}
return(result)
}
# Test the functions with an example input
number <- 5
result_recursion <- factorial_recursion(number)
result_iteration <- factorial_iteration(number)
# Print the results
cat("Factorial of", number, "using recursion is:", result_recursion, "\n")
cat("Factorial of", number, "using iteration is:", result_iteration, "\n")
Output:
Factorial of 5 using recursion is: 120 Factorial of 5 using iteration is: 120
Explatnaion:
In the exercise above,
- The "factorial_recursion()" function calculates the factorial of a given number using recursion. It checks if the number is 0 (base case) and returns 1. Otherwise, it recursively calls itself with 'n - 1' until 'n' becomes 0.
- The "factorial_iteration()" function calculates the factorial of a given number using iteration (for loop). It initializes a variable 'result' to 1 and then iterates from 1 to 'n', multiplying 'result' by each number in the loop.
- Both functions are tested with an example input (number = 5), and the results are printed to the console.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Generate Pascal's Triangle with For loops in R.
Next: Calculate Sum of Odd elements in Array using For loop in R.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics