Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Factorial in Java

Find a factorial in Java with Scanner and a for loop that multiplies into long. The guard accepts 0–20 only: 0! is 1, while 21! exceeds the long range.

BeginnerJava Loop ProgramsExample 4 of 25
factorial.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter n: ");
7 int n = sc.nextInt();
8
9 if (n < 0 || n > 20) {
10 System.out.println("Enter n from 0 to 20");
11 sc.close();
12 return;
13 }
14
15 long fact = 1;
16 for (int i = 1; i <= n; i++) {
17 fact *= i;
18 }
19
20 System.out.println("Factorial = " + fact);
21 sc.close();
22 }
23}

Sample Output

Enter n: 5
Factorial = 120

Start fact=1. At i=1,2,3,4,5 the values are 1,2,6,24,120. Only 120 is printed.

In this one

  • Build a running product
  • Explain why 0! equals the starting value
  • Limit inputs to fit long

How it works

  1. 1

    Read n and check that it is 0 through 20.

  2. 2

    Set fact to 1.

  3. 3

    Multiply fact by i for i = 1 through n.

  4. 4

    Print the final product.

Edge cases

Zero factorial

Enter 0

No multiplications run and fact remains 1, the correct value of 0!.

Too large or negative

Enter 21 or -1

The guard rejects the input instead of returning a wrapped or meaningless result.

What's going on

The factorial of n is the product of the whole numbers from 1 through n. It is written n!. For example, 5! means 1 * 2 * 3 * 4 * 5. Factorials appear in counting arrangements, such as the orders in which a few students can stand in a line.

Scanner is the keyboard reader. The code reads n and starts fact at 1. A for loop multiplies fact by each i from 1 through n. The running product is saved after every pass instead of printing separate multiplication results. long is a whole-number type with more room than int.

For 5, fact goes through 1, 2, 6, 24, and 120. Starting fact at zero would make the whole answer zero. The allowed range here is 0 through 20: 0! is 1 and fits the starting value, while 21! is too large for long. The input guard rejects negative values and values above 20 before the loop.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is 4 factorial?

Pick an answer to check it.

Question 2

What does input 0 return?

Pick an answer to check it.

Questions people ask

Why is fact not zero at the start?

Multiplying by zero would erase every later factor. One is the starting value for a product.

What is the largest supported n here?

20. Its factorial fits long; 21 factorial does not.

Does the loop add 1 through n?

No. It multiplies them. The sum-of-series exercise uses addition instead.