# JAVA PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER

FACTORIAL : Factorial is a mathematical term that is used to calculate the product of an integer. Factorial of a number n can be calculated as n! (here value of n! is 1*2*3*4 ... (n-1)*n)

Assume you have to calculate the factorial of a number say 6, its factorial can be calculated as 5!= 5 *4 * 3 * 2 * 1 which is equal to 120. Lets see the implementation with Java program.

[hide]
• Java Program of Factorial using For Loop
• Java Program of Factorial using While Loop
• Java Program of Factorial using Recursion

### Example 1 : Java Program of Factorial using For Loop

``````// Java program to calculate factorial of any number
import java.util.Scanner;
class FactorialDemo{
static int findfactorial(int n){
int fact=1;

for(int i=n ; i>0 ; i-- ) {
fact= fact*i;
}
return fact;
}
}

public class Codebator{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any Number");
int num=sc.nextInt();
int result=FactorialDemo.findfactorial(num);
System.out.println("Factorial of the given number s : "+result);
}
}
``````

#### OUTPUT :

`Enter any Number5 120 `

### Example 2 : Java Program of Factorial using While Loop

``````// Java program to calculate factorial of any number
import java.util.Scanner;
class FactorialDemo{
static int findfactorial(int n){
int fact = 1,i=1;

while(i <= n) {
fact = fact * n;
n--;
}
return fact;
}
}

public class Codebator{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any Number");
int num=sc.nextInt();
int result=FactorialDemo.findfactorial(num);
System.out.println("Factorial of the given number s : "+result);
}
}
``````

#### OUTPUT :

`Enter any Number7 5040 `

### Example 2 : Java Program of Factorial using Recursion

``````// Java program to calculate factorial of any number
import java.util.Scanner;
class FactorialDemo{
static int findfactorial(int n){
if (n == 0)
return 1;
else
return(n * findfactorial(n-1));
}
}

public class Codebator{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any Number");
int num=sc.nextInt();
int result=FactorialDemo.findfactorial(num);
System.out.println("Factorial of the given number s : "+result);
}
}
``````

#### OUTPUT :

`Enter any Number8 40320 `