The 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. The notation used for factorial is '!' and the formula used is n! =n * (n-1) * (n-2) *... To understand this concept clearly, some examples are given below in the picture.
Note: The factorial of zero is defined as one ie., 0 ! = 1
Here in this R program, we make use of if...else conditional
statements and for loop
. First, we accept a number as the user's input into the variable number by providing an appropriate message to the user using the 'prompt
' inside the readLine()
function.
The factorial is defined for only positive integers, so first check the entered number is positive, if not display it's a negative integer. Now check If the number is zero then display the factorial as 1. Now for a positive integer, start a for loop
from i= 1 to that number and multiply each 'i value' with the 'factorial' in every iteration to get the final result of that number. Finally, show output to the user.
STEP 1: Prompting appropriate messages to the user take user input using readline()
into a variable
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
If you are interested to learn this R program using recursion, please refer to this factorial program using recursion.
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))
}
Enter a number: -5 [1] "Sorry, factorial does not exist for negative numbers" Enter a number: 0 [1] "The factorial of 0 is 1" Enter a number: 8 [1] "The factorial of 8 is 40320"