# Factorial Program in Java Using Loop and Recursion

Here you will get factorial program in java using loop and recursion.

What is Factorial?

We can find factorial of any number by repeatedly multiplying it with all the numbers below it which are greater than 0. For example factorial of 3 is 6 (1 x 2 x 3).

## Factorial Program in Java Using Loop

import java.util.Scanner;

public class JavaFactorial {
public static void main(String args[]) {
int n, i, fac = 1;
Scanner sc = new Scanner(System.in);

System.out.println("enter a number: ");

n = sc.nextInt();

//factorial of 0 is 1
if(n == 0){
System.out.println("factorial = " + fac);
}
else {
for(i = 1; i <= n; ++i){
fac *= i;
}

System.out.println("factorial = " + fac);
}
}
}

Output

enter a number:
6
factorial = 720

## Factorial Program in Java Using Recursion

import java.util.Scanner;

public class JavaFactorial {
public static void main(String args[]) {
int n, fac = 1;
Scanner sc = new Scanner(System.in);

System.out.println("enter a number: ");

n = sc.nextInt();

//factorial of 0 is 1
if(n == 0){
System.out.println("factorial = " + fac);
}
else {
fac = factorial(n);
System.out.println("factorial = " + fac);
}
}

public static int factorial(int n){
if(n < 1){
return 1;
}

return n * factorial(n - 1);
}
}

Comment below if you have any doubts regarding java factorial program.