Calculate the Factorial of a Number using Loop
Last Updated :
25 Sep, 2023
In this article, we will discuss how to calculate the factorial of a number with its working example in the R Programming Language using R while loop. In R programming, loops are essential constructs that allow us to repeat a set of instructions multiple times. The while loop is one such construct that repeatedly executes a block of code until a certain condition is met. This loop is particularly useful when you want to iterate over elements without knowing the exact number of iterations in advance. In this article, we will explore how to use the while loop to print the factorial of a number and understand its step-by-step implementation.
Formula of factorial:
fact(N)=N*fact(N-1)
Syntax:
factorial <- function(n) {
result <- 1
while (n > 0) {
result <- result * n
n <- n - 1
}
return(result)
}
Example 1: Calculate factorial of 5
R
factorial <- function (n) {
result <- 1
while (n > 0) {
result <- result * n
n <- n - 1
}
return (result)
}
factorial (5)
|
Output:
[1]120
- First we will initialize result=1.
- Then we create a while loop with the condition 5 > 0.
- This loop will run as long as 5 is greater than zero.
- Multiply the result by the value of 5.
- Decrement the value of n by 1.
- After the loop, return the value of result as the calculated factorial.
Example 2: Calculate factorial of 10
R
factorial <- function (n) {
result <- 1
while (n > 0) {
result <- result * n
n <- n - 1
}
return (result)
}
factorial (10)
|
Output:
[1] 3628800
- First we will initialize result=1.
- Create a while loop with the condition 10 > 0.
- This loop will run as long as 10 is greater than zero.
- Multiply the result by the value of n.
- Decrement the value of 10 by 1.
- After the loop, return the value of result as the calculated factorial.
Example 3: Calculate factorial using user defined value
R
number <- as.integer ( readline ( "Enter a positive integer: " ))
factorial <- 1
var <- 2
while (var <= number) {
factorial <- factorial * var
var <- var + 1
}
cat ( "Factorial:" , factorial, "\n" )
|
Output:
Factorial: 5040
number <- as.integer(readline("Enter a positive integer: "))
: This line prompts the user to input a positive integer using the readline
function. It then converts the input to an integer and assigns it to the variable number
.in this we passed value 7.
factorial <- 1
: Here, we initialize the factorial
variable to 1
. This variable will be used to store the calculated factorial value.
var<- 2
: We set the initial value of the var
variable to 2
. This is because we want to start the multiplication from 2
.
- Once the loop finishes, the calculated factorial will be stored in the
factorial
variable.
cat()
: This line uses the cat
function to print the calculated factorial value along with the text “Factorial:”. The "\n"
is used to add a newline character to improve formatting.
Share your thoughts in the comments
Please Login to comment...