In Java, you can use a loop to calculate the factorial of a number. A factorial is the product of an integer and all the integers below it; for example, the factorial of 4 is 4 * 3 * 2 * 1 = 24.
Here's an example of how to use a loop to calculate the factorial of a number in Java:
public class Main { public static void main(String[] args) { int num = 4; int factorial = 1; for (int i = 1; i <= num; i++) { factorial *= i; } System.out.println(factorial); // 24 } }
In this example, a for
loop is used to iterate over the integers from 1 to num
. The loop variable i
is initialized to 1 and is incremented by 1 on each iteration until it reaches num
. The factorial is calculated by multiplying i
by the current value of factorial
on each iteration.
This code will calculate the factorial of 4 and print the result to the console. You can use a loop to calculate the factorial of any number in Java.