R Program to find the factorial of a number

How to find the factorial of a number

Factorial of a number N is the total product of all numbers from 1 to that number in other words it multiplies all whole numbers from our chosen number down to 1. Factorial is only defined for positive integers and not available to negative integers. The notation used for factorial is ! and formula used for factorial is n! =n x (n-1) x (n-2) x ... x 2 x 1. To understand this concept clearly, some examples are given below in the picture.

Find the factorial of a number

Note: The factorial of zero is defined as one ie., 0 ! = 1

How factorial calculation is implemented in R Program

Are you interested in the recursive methods? We already have a factorial program using recursion in our R program section.

Here in this simple R program, we make use of if...else conditional statements and for loop to implement the factorial calculation. 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 a number to find factorial as the user's input into the variable number by providing an appropriate message to the user using 'prompt' inside the readLine() function. As we already discussed the factorial is defined for only positive integers first check the entered number is positive, if not display it's a negative integer. If the number is zero then display factorial as 1. And for a positive integer start a for loop from i= 1 to that number and multiply each i  with previous in every iteration to get the final product as Factorial of that number. Finally, show output to the user.

ALGORITHM

STEP 1: Prompting appropriate messages to the user take user input using readline() into variable number

STEP 2: Check if the number is negative, zero, or positive using if...else statement

STEP 3: If the number is positive, we use for loop to calculate the factorial as factorial = factorial x i till i = 1 to number

STEP 4: 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"