In this program, you'll learn to find the factorial of a number using for and while loop in Java.

The factorial of a positive number `n` is given by:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

```
public class Factorial {
public static void main(String[] args) {
int num = 10;
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}
```

When you run the program, the output will be:

Factorial of 10 = 3628800

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`.

We've used `long` instead of `int` to store large results of factorial. However, it's still not big enough to store the value of bigger numbers (say 100).

For results that cannot be stored in a long variable, we use `BigInteger`

variable declared in `java.math`

library.

```
import java.math.BigInteger;
public class Factorial {
public static void main(String[] args) {
int num = 30;
BigInteger factorial = BigInteger.ONE;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}
```

When you run the program, the output will be:

Factorial of 30 = 265252859812191058636308480000000

Here, instead of `long`

, we use `BigInteger`

variable factorial.

Since, `*`

cannot be used with `BigInteger`

, we instead use `multiply()`

for the product. Also, `num` should be casted to `BigInteger`

for multiplication.

Likewise, we can also use a while loop to solve this problem.

```
public class Factorial {
public static void main(String[] args) {
int num = 5, i = 1;
long factorial = 1;
while(i <= num)
{
factorial *= i;
i++;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}
```

When you run the program, the output will be:

Factorial of 5 = 120

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.

Visit this page to learn to *find factorial of a number using recursion*.

It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:

**Disabling AdBlock on Programiz. We do not use intrusive ads.**

or

Donate on Paypal
By using Programiz, you agree to use cookies as stated in our Privacy policy Continue