Ass Soln2
Ass Soln2
3) Develop a program to find the factorial of given number using recursive function
calls.
Soln: # Define a recursive function to calculate the factorial
factorial <- function(n) {
# Base case: if n is 0 or 1, the factorial is 1
if (n == 0 || n == 1) {
return(1)
}
# Recursive case: n * factorial of (n - 1)
else {
return(n * factorial(n - 1))
}
}
If there are many else statements, it looks confusing and in such cases the switch() function
is required. The first argument of the switch statement is an expression that can return a
string value or an integer. This is followed by several named arguments that provide the
results when the name matches the value of the first argument. Here also we can execute
multiple statements enclosed by curly braces. If there is no match the switch statement
returns NULL. So, in this case, it is safe to mention a default value if none matches
Faculty HOD