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
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
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
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 thereadline
function. It then converts the input to an integer and assigns it to the variablenumber
.in this we passed value 7. -
factorial <- 1
: Here, we initialize thefactorial
variable to1
. This variable will be used to store the calculated factorial value. -
var<- 2
: We set the initial value of thevar
variable to2
. This is because we want to start the multiplication from2
. -
Once the loop finishes, the calculated factorial will be stored in the
factorial
variable. -
cat()
: This line uses thecat
function to print the calculated factorial value along with the text “Factorial:”. The"\n"
is used to add a newline character to improve formatting.