Factorial of a positive integer n is multiplication of all positive integers from n till 1. Factorial is written as n!.
5! = 5 x 4 x 3 x 2 x 1 = 120
Factorial of zero is considered as 1
Finding Factorial using a loop
package com.techstackjournal.java.basics;
public class FactorialNumberExample1 {
public static void main(String[] args) {
int n = 3;
int factorial = factorial(n);
System.out.println("Factorial of " + n + " is " + factorial);
}
private static int factorial(int n) {
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial = factorial * i;
}
return factorial;
}
}
Finding Factorial using Recursive Function
package com.techstackjournal.java.basics;
public class FactorialNumberExample2 {
public static void main(String[] args) {
int n = 3;
int factorial = factorial(n);
System.out.println("Factorial of " + n + " is " + factorial);
}
private static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}