R Program to find the factorial of a number

How to find the factorial of a number

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.

How factorial calculation is implemented in R Program

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.

ALGORITHM

STEP 1: prompting appropriate messages to the user

STEP 2: take user input using readline() into variables number

STEP 3: check if the number is negative, zero, or positive using if...else statement

STEP 4:If the number is positive, we use for loop to calculate the factorial

STEP 5:print the result

R Source Code

                                          number = as.integer(readline(prompt="Enter a number: "))
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))

                                      

OUTPUT

Enter a number: 8
[1] "The factorial of 8 is 40320"