# Factorial program in Java

A classic program in Java is the Factorial Calculator.

###### What is the factorial of a number?

According to the Britannica:

Factorial, in mathematics, the product of all positive integers less than or equal to a given positive integer and denoted by that integer and an exclamation point. Thus, factorial seven is written 7! meaning 1 × 2 × 3 × 4 × 5 × 6 × 7. Factorial zero is defined as equal to 1.

In everyday life, we use factorial as the total number of arrangements. It means we can arrange n objects in n! different ways.

###### How is calculated the factorial of a number?

The factorial of a number n is the product of all numbers from 1 to n.

Based on this rule, let’s write the algorithm of the factorial calculator.

Step 1: Declare the variable i, and initialize it to 1.
Step 2: Declare the variable result, which will store the factorial, and initialize it to 1;
Step 3: Read the variable n.
Step 4: The result is multiplied with i, and the product is stored in the variable result.
Step 5: Repeat step 4, for each i, from 1 to n.

The next step is to implement this algorithm in Java.

###### The factorial program in Java

Each program in Java is within a class. We will implement the calculation part inside a method called calculateFactorial.

`static void calculateFactorial(int n)`

Let’s build the loop for, which will calculate the product of each number, from 1 to n.

```for(i = 1; i <= n; i++){
fact = fact * i;
}```

The complete code of this example in Java is:

```public class FactorialProgram {
static void calculateFactorial(int n) {
int i;
int fact = 1;
for(i = 1; i <= n; i++){
fact = fact * i;
}
System.out.println("Factorial of "+n+" is: "+fact);
}
public static void main(String[] args) {
calculateFactorial(5);
}
}

```

In Console:

`Factorial of 5 is: 120`
###### a recursive Version

The nature of the algorithm is recursive: the calculations for the factorial of n are based on the factorial of (n-1). Let’s try to implement the recursive version of the factorial program.

The base condition is:

`if (n == 0)`

This means the recursion will stop when n is equal to zero. Otherwise, the method calls itself, but with another parameter, which will be (n-1).

`factorial(n-1)`

The code of the recursive version of the factorial program in Java is this one:

```class FactorialRecursiveProgram{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int fact=1;
int number=4;
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}```

In Console:

`Factorial of 4 is: 24`

Hopefully, this will help you understand this classic problem, solved in both iterative and recursive ways.