Factorial means multiplying all whole numbers from the chosen number down to one. The java programme will store a number in a variable to find the factorial of that number. The programme will multiply positive integer numbers beginning with 1 until it reaches the specified number. The result of the number multiplication is the factorial of the given number. In this post, we’ll look at how to write a Java programme that calculates the factorial of a number.

## Factorial of a Number

The product of all positive descending integers is the factorial of a number ‘n.’ n represents the factorial of n. Factorial means multiplying all whole numbers from the chosen number down to one. The example below shows how to calculate the factorial by multiplying the positive integer numbers. In the example, the factorial series are shown.

1! = 1 2! = 1 * 2 3! = 1 * 2 * 3 4! = 1 * 2 * 3 * 4 5! = 1 * 2 * 3 * 4 * 5 . . . . . . . . . . . . . n! = 1 * 2 * 3 * 4 * 5 * . . . . * n

There are two methods for calculating the factorial of a number. The simplest method is to use a loop to iterate from 1 to n times and multiply the numbers. The second approach uses the recursive method.

## Java Program to Find Factorial of a Number Using Loop

The for loop is used in the java example program below to find the factorial of a number. To find the factorial of 5, the for loop iterates from 1 to 5. The most important aspect of the program is that the variable fact be initialized with the value 1. The for loop index value I should be set to 1. The for loop should execute including the factorial value. The condition in the for loop should be “less than or equal to ( <= )”.

package in.yawin; public class Factorial { public static void main(String[] args) { int value = 5; int fact = 1; for (int i = 1; i <= value; i++) { fact = fact * i; } System.out.println("Factorial value of " + value + " is " + fact); } }

### Output

Factorial value of 5 is 120

## Java Program to Find Factorial of a Number Using Recursive Method

There should be two methods if you want to use a recursive method: calling method and recursive method. In this case, the calling method is the java main method. The recursive method is called “fact.”

Three points should be kept in mind when writing a recursive method. The first of these is the exit condition. The second is the return value, and the third is that the method be called recursively.

package in.yawin; public class Factorial { public static void main(String[] args) { int value = 5; int f = fact(value); System.out.println("Factorial value of " + value + " is " + f); } public static int fact(int value) { if(value==0) return 1; return value * fact(value-1); } }

### Output

Factorial value of 5 is 120