Factorial of a number is the product of the numbers from 1 to that number. For example factorial of 3, denoted as 3! and the value is 3x2x1 = 6.
In java we can find a factorial in two ways, using for-loop and using function (calling recursively).
Finding Factorial Using for loop:
public static void main(String[] args){
int var = 6;
int result = 1;
for (int i = 1; i <= var; i++)
result = result * i;
System.out.println("Factorial of " + var + " is " + result);
}
Finding Factorial Using Recursion
public class FactorialFinder { int factorial(int n){ if(n==1) return 1; else return n*fact(n-1); } public static void main(String[] args) { int result = factorial(1); System.out.println("Factorial 1! = " + result); result = factorial(5); System.out.println("Factorial 5! = " + result); result = factorial(7); System.out.println("Factorial 7! = " + result); } }
So you can practice on your compiler. Tank you.