
Home 

In this article you will learn how to find factorial of a number in R programming using while loop, for loop and recursion (with a recursive function).
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.
If you want to learn R step by step for data analysis or data science with Practical Examples, I will suggest you to see this simple and to the point R Programming Course with Exercises and Projects.
In this example you will find factorial using a for loop.
For understanding this example you should know the basics of
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 another 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)
[1] "Factorial of
negative numbers is not possible"
> findfact(0)
[1] "Factorial of
0 is 1"
> findfact(5)
[1]
"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.
For understanding this example you should know the basics of
#Factorial with recursive function