java program to print factorial of a number

Here is a java program to print factorial of a number. In this program first user input the number then the program calculate the factorial, then user see the result.

java program to print factorial of a number

Source Code:

import java.util.Scanner;
//java program to print factorial of a number
public class findFact {
    public static void main(String s[]) {
        int num, fact = 0;
	Scanner sc = new Scanner(System.in);
	try {
            System.out.print("Enter number:");
	    num = sc.nextInt();
	    fact = num; 
	    //fact
	    for(int i = 1; i<= num-1; i++) {
	        fact = fact * (num - i);
	    }
	    System.out.printf("Factorial of %d is %d.",num,fact);
	}
	finally {
	    sc.close();
	}
    }
}

Input & Output:

Enter number:4
Factorial of 4 is 24.

Recommended Post