Program to find the factorial of a number by iterative method:
package quipoin.javaeasyprograms;
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // scanner class for taking input
System.out.println("Enter the value: ");
int n = sc.nextInt();
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
System.out.println("Factorial of "+n+" is "+fact);
sc.close();
}
}
Output:
Enter the value:
5
Factorial of 5 is 120
Program to find factorial by the recursive method:
package quipoin.javaeasyprograms;
public class FactorialRecursion {
static int factorial(int n) {
if (n == 1 || n == 0)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
Output:
120