Here we are explaining how to write an R program to find the factorial of a number. We can use the readline() function to take input from the user (terminal). Here the prompt argument can choose to display an appropriate message for the user.
We are using readline() function for taking the user’s input. Given below are the steps which are used in the R program to find the factorial of a number. In this R program, we accept the user’s input into the variable number by providing an appropriate message to the user using ‘prompt’. The factorial of a number is the product of all the integers from 1 to that number. The factorial of zero is one and Factorial is not defined for negative numbers.
number = as.integer(9)
factorial = 1
# check is the number is negative, positive or zero
if(number < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(number == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:number) {
factorial = factorial * i
}
}
print(paste("The factorial of", number ,"is",factorial))
## [1] "The factorial of 9 is 362880"
number = as.integer(5)
factorial = 1
# check is the number is negative, positive or zero
if(number < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(number == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:number) {
factorial = factorial * i
}
}
print(paste("The factorial of", number ,"is",factorial))
## [1] "The factorial of 5 is 120"