Factorial in Java

Find factorial of a number using a loop.

BeginnerModule 3: 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 long fact = 1;
10 for (int i = 1; i <= n; i++) {
11 fact *= i;
12 }
13
14 System.out.println("Factorial = " + fact);
15 sc.close();
16 }
17}

Output

Enter n: 5
Factorial = 120

What's going on

We multiply numbers from 1 to n to compute n!.