In this program, You will learn how to find the factorial of a number in R.
Example: How to find the factorial of a number in R
1 2 3 4 5 6 7 8 9 10 11 12 | { x <- as.integer(readline(prompt = "Enter a number :")) f = 1 for (i in 1:x) { f = f * i } print(paste("Factorial is :", f)) } |
The output of this program would depend on the value of x
that is entered by the user. Here is an example of what the output might look like:
1 2 3 4 | Enter a number :5 [1] "Factorial is : 120" |
In this example, the user entered 5 as the number, and the program calculates the factorial of 5, which is 120. The factorial of a number is the product of all the positive integers from 1 up to that number. For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120.
The program first reads the number from the user using the readline()
function and stores it in the variable x
. It then initializes the variable f
to 1, which is the starting value for the factorial.
The for
loop iterates over the sequence of numbers from 1 to x
, and on each iteration, the value of i
is updated to the current number in the sequence. The variable f
is updated to be the current value of f
multiplied by the current value of i
.
After the loop completes, the final value of f
is printed to the console using the print()
function. In this case, the final value of f
is 120, which is the factorial of 5.