In this Java program, we’ll learn how to find the factorial of a number in your Java program.
How to Find the Factorial of a Number?
Example 1: using loop
RUN CODE SNIPPETclass Main{ public static void main(String args[]){ int i,fact=1; int number=6; for(i=1;i<=number;i++){ fact=fact*i; } System.out.println("Factorial of "+number+" is: "+fact); } }
OUTPUT
Factorial of 6 is: 720
Example 2: using recursion
RUN CODE SNIPPETclass Main{ static int factorial(int n){ if (n == 0) return 1; else return(n * factorial(n-1)); } public static void main(String args[]){ int i,fact=1; int number=5; fact = factorial(number); System.out.println("Factorial of "+number+" is: "+fact); } }
OUTPUT
Factorial of 5 is: 120