The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
Example 1: Using for loop
public class Factorial { public static void main(String[] args) { int num = 9; |
Output :
Factorial of 9 = 362880
In this program, we've used for loop to loop through all numbers between 1 and the given number num(10), and the product of each number till num is stored in a variable factorial.
Example 2: Using while loop
public class Factorial { public static void main(String[] args) { int num = 9, i = 1; |
Output :
Factorial of 9 = 362880
In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.
Though both programs are technically correct, it is better to use for loop in this case. It's because the number of iteration (upto num) is known.