Open In App

Calculate the Factorial of a Number using Loop

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

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

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 

Article Tags :