Program to calculate Factorial of given number.
/**
* This program is used to calculate Factorial of given number.
* @author W3schools360
*/
public class Factorial {
/**
* This method is used to calculate Factorial of given no.
* @param num
*/
static void factorialNumber(int num){
int fact = 1;
//Factorial of 0 and 1 is 1.
if(num == 0 || num == 1){
System.out.println("factorial of " + num + " is 1.");
}
//for calculating factorial, number should be non negative.
if(num > 0){
//calculate factorial.
for(int i = 2; i <= num; i++){
fact = fact*i;
}
System.out.println("factorial of " + num + " is " +fact);
}else{
System.out.println("no. should be non negative.");
}
}
public static void main(String args[]){
//method call
factorialNumber(5);
}
}
Output:
factorial of 5 is 120