Java Factorial Program @Lifebix

Java Factorial Program: Factorial of n is the product of all positive integers. n is denoted by n!. For example:

6! = 6*5*4*3*2*1 = 720
4! = 4*3*2*1 = 24
Here, 6! is pronounced as “4 factorial”, it is also called “6 bang” or “6 shriek”.

In java language many ways to write the factorial program . Let’s see the “TWO” ways to write the factorial program in java.

(i)Factorial Program using loop
(ii)Factorial Program using recursion

(i)By using for loop write the Factorial Program:

class FactorialExp1{
public static void main(String args[]){
int K,factorial=1;
int num=6;//It is the number to calculate factorial
for(K=1;K<=number;K++){
factorial=factorial*K;
}
System.out.println(“Factorial of “+num+” is: “+factorial);
}
}

Output:
factorial of 6 is 720

(ii)Using recursion Write the Factorial Program in java :

class FactorialExp2{
static int factorial(int number){
if (number == 0)
return 1;
else
return(number * factorial(number-1));
}
public static void main(String args[]){
int j,factorial=1;
int num=5;//It is the number to calculate factorial
factorial = factorial(num);
System.out.println(“Factorial of “+num+” is: “+factorial);
}
}

Output:
factorial of 5 is 120

Leave a Reply

Your email address will not be published.