1. Introduction
This R program calculates the factorial of a number using recursion. Recursion is a technique in programming where a function calls itself. The factorial of a number n is the product of all positive integers less than or equal to n.
2. Program Steps
1. Define a function to calculate factorial using recursion.
2. Call the function with a specific number.
3. Print the result.
3. Code Program
# Step 1: Define a function to calculate factorial using recursion
factorial <- function(n) {
if(n <= 1) {
return(1)
} else {
return(n * factorial(n - 1))
}
}
# Step 2: Call the function with a specific number
number <- 5
result <- factorial(number)
# Step 3: Print the result
print(paste("Factorial of", number, "is:"))
print(result)
Output:
Factorial of 5 is: [120]
Explanation:
1. factorial <- function(n) { ... }: Defines a recursive function factorial. If n is less than or equal to 1, it returns 1. Otherwise, it returns n multiplied by the factorial of n-1.
2. number <- 5: Specifies the number for which to calculate the factorial.
3. factorial(number): Calls the factorial function with the specified number.
4. print(paste("Factorial of", number, "is:")), print(result): Prints the factorial of the given number.
Comments
Post a Comment