w3resource

Calculate Factorial using While loop in R

R Programming: Control Structure Exercise-2 with Solution

Write a R program that creates while loop to calculate the factorial of a given number.

Sample Solution :

R Programming Code :

# Function to calculate the factorial of a given number
calculate_factorial <- function(n) {
    # Initialize variables
    fact <- 1
    i <- 1
    
    # Check if the entered number is negative
    if (n < 0) {
        print("Factorial is not defined for negative numbers.")
    } else if (n == 0) { # Check if the entered number is 0
        print("Factorial of 0 is 1.")
    } else { # Calculate factorial using a while loop
        while (i <= n) {
            fact <- fact * i
            i <- i + 1
        }
        # Return the factorial of the entered number
        return(fact)
    }
}

# Call the function to calculate the factorial of a given number
number <- 5 # Example: Calculate factorial of 5
factorial_result <- calculate_factorial(number)

# Print the factorial result
cat("Factorial of", number, "is", factorial_result, ".\n")

Output:

Factorial of 5 is 120                  

Explatnaion:

In the exercise above,

  • calculate_factorial Function:
    • This function calculates the factorial of a given number 'n'.
    • It initializes variables 'fact' and 'i' to 1, where 'fact' will store the factorial result and i is a counter for the loop.
    • The function first checks if the given number 'n' is negative. If so, it prints a message stating that factorial is not defined for negative numbers.
    • If n is not negative, the function then checks if 'n' is equal to 0. If so, it prints a message stating that the factorial of 0 is 1.
    • If n is positive, the function enters a while loop where it calculates the factorial iteratively by multiplying 'fact' with 'i' until 'i' reaches 'n'.
    • After the loop, the function returns the calculated factorial value.
  • Main Code:
    • Outside the function, a number (in this case, 5) is assigned to the variable 'number', representing the number whose factorial needs to be calculated.
    • The "calculate_factorial()" function is then called with the 'number' as an argument, and the result is stored in the variable 'factorial_result'.
    • Finally, the result is printed to the console using 'cat'.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Printing Numbers from 1 to 10 using For loop in R.
Next: Sum of Even numbers using For loop in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/control-structure/r-programming-control-structure-exercise-2.php