Factorial Example Java Program


Definition

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! = 5*4*3*2*1 = 120

Factorial Example Program

import java.util.Scanner;

public class FindFactorial {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("Enter the number: ");
		int num = in.nextInt();
		int result = factorialMethod(num);
		System.out.println("The factorial of " + num + " is " + result);
	}
	public static int factorialMethod(int num) {
		int result = 1;
		for (int i = 1; i <= num; i++) {
			result = result * i;
		}
		return result;
	}
}

Sample Output

Output is:
Enter the number: 8
The factorial of 8 is 40320