Back to: Java Tutorials

Factorial is a mathematical function that calculates the product of all positive integers up to a given number. It is denoted by the symbol “!” and is read as “factorial”. For example, the factorial of 5, denoted as 5!, is calculated as:

5! = 5 x 4 x 3 x 2 x 1 = 120

Factorial has many applications in mathematics and science, including probability theory, combinatorics, and the binomial theorem. In programming, the factorial function is often used as a basic example to demonstrate recursion and iteration.

Here is an example of Java code to calculate the factorial of a given number using **recursion**:

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

In this code, the `main`

function initializes the variable `n`

to 5 and then calls the `factorial`

function to calculate the factorial of `n`

. The result is then printed to the console.

The `factorial`

function takes an integer `n`

as input and recursively calculates the factorial of `n`

. If `n`

is equal to 0, then the function returns 1. Otherwise, the function multiplies `n`

by the result of calling `factorial`

with `n-1`

as input. This continues until `n`

reaches 0, at which point the function returns 1.

When this code is executed, it will output the message “Factorial of 5 is 120” to the console.

Here is an example of Java code to calculate the factorial of a given number using **iteration**:

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

In this code, the `main`

function initializes the variable `n`

to 5 and then calls the `factorial`

function to calculate the factorial of `n`

. The result is then printed to the console.

The `factorial`

function takes an integer `n`

as input and uses a `for`

loop to iteratively calculate the factorial of `n`

. The function initializes `result`

to 1 and then multiplies it by each integer from 1 to `n`

, inclusive. Once the loop finishes, the function returns the value of `result`

.

When this code is executed, it will output the message “Factorial of 5 is 120” to the console.

Follow us on social media

Follow Author