 # Factorial of a Number in R

You will learn how to find factorial of a number in R programming with for loop (Examples) avoiding the use of recursive function.

## Factorial

To understand factorial see this example

4! = 1*2*3*4 = 24

The factorial of 4 is 24. Factorial of any number is the product of all numbers from 1 to that number. However the factorial of 0 is defined as 1 and negative numbers don't have factorial.

For understanding this example you should know the basics of

for loop in R

if else structure in R

### Symbol

The symbol of factorial is "!" i.e "exclamatory mark" which is put after the number like 4!

### R Example

Factorial in R can be found with for loop or with recursive function. Here we will find factorial with a for loop.

findfactorial <- function(n){

factorial <- 1

if ((n==0)|(n==1))
factorial <- 1

else{
for( i in 1:n)
factorial <- factorial * i
}
return (factorial)
}

In this simple example we have defined a function findfactorial which takes one argument, which is the number for which we want to find factorial. A variable named factorial is defined and as minimum factorial can be 1 so we have assigned 1 to that variable. After that we are using if else structure. If number is 0 or 1 then the factorial is 1 hence this is the if condition. In else block, the number is more than 1 and it means the factorial can be calculated by muliplying all numbers from 1 to that number. We have used a variable i which goes from 1 to the number and for each iteration of for loop, the product is multiplied by i. In the end a return statement is used to return factorial from this function. Ofcourse this can be done without using a function but with function the logic is with more clarity and you also learn to develop functions as R programming is done using functions as basic units and you can call these functions again and again.

After grasping the logic of factorial in R code, now you can write code for another R program which finds factorial of number taken as input from user. Here is a program in Rstudio

findfact <- function(n){
factorial <-1

if(n<0)
print("Factorial of negative numbers is not possible")
else if(n==0)
print("Factorial of 0 is 1")
else {
for(i in 1:n)
factorial <- factorial * i

print(paste("Factorial of ",n," is ",factorial))
}

>findfact(-3)
 "Factorial of negative numbers is not possible"
> findfact(0)
 "Factorial of 0 is 1"
> findfact(5)
 "Factorial of 5 is 120"

There is a builtin function in R Programming to calculate factorial, factorial() you may use that to find factorial, this function here is for learning how to write functions, use for loop, if else and if else if else structures etc.

Learn how to calculate factorial with Recursion

#### Learn to Shine

• Programming made Easy for all
• High School and College
• University level
• Professionals doctors, engineers, scientists
• Data Analysts