Factorial Program in Java and Examples
Factorial: Factorials are products of every whole number from 1 to n Factorials are introduced in algebra. The value of 0! is 1, according to the convention for an empty product. The notation n! was introduced by the French mathematician Christian Kramp in 1808.
Formula:
n! = n(n-1)(n-2)(n-3)(2)(1)
(or)
n! = n.(n-1)!.
Example:
4! = 4*(4-1)*(4-2)*(4-3)*(4-4)
4! = 4*3*2*1
4! = 24
Factorial Program in Java:
Factorial Program:
class Fact
{
public static void main(String args[])
{
int fact = 1,j = 6;
for(int i = 1;i<=j;i++)
{
fact = fact * i ;
}
System.out.println("Fact of 6 = "+fact);
}
}
Output:
Fact of 6 = 720
Factorial program in Java using user entered value:
Java Factorial program:
import java.util.Scanner;
class Fact1
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int fact = 1;
System.out.print("Enter the value of j = ");
int j = s.nextInt();
for(int i = 1;i<=j;i++)
{
fact = fact * i ;
}
System.out.println("Fact of " + j + " = " +fact);
}
}
Output:
Enter the value of j = 10
Fact of 10 = 3628800
Factorial program in Java using recursion:
Java Factorial recursion program:
class FactorialRecursion
{
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;
FactorialRecursion f1 = new FactorialRecursion();
fact = f1.factorial(5);
System.out.println("Factorial of 5 = "+fact);
}
}
Output:
Factorial of 5 = 120
Factorial program in Java:
Recursion program using user entered value:
Java Recursion Factorial program using user entered value:
import java.util.Scanner;
class FactorialRecursion1
{
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;
Scanner s = new Scanner(System.in);
FactorialRecursion1 f1 = new FactorialRecursion1();
System.out.print("Enter the value of J = ");
int j = s.nextInt();
fact = f1.factorial(j);
System.out.println("Factorial of J = "+fact);
}
}
Output:
Enter the value of J = 6
Factorial of J = 720