# Factorial program in Java

(Last Updated On: 11/10/2023)

Factorial is a mathematical operation used to find the product of all positive integers less than or equal to a given number. In programming, we often need to calculate the factorial of a given number. In this blog, we will explore how to write a factorial program in Java using different techniques.

## What is a factorial program in Java?

A factorial program in Java is a program that calculates the factorial of a given number. The factorial of a number n is denoted by n! and is defined as the product of all positive integers less than or equal to n. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120.

Know the Palindrome Program in Java here!

## Methods to Create a Factorial Program in Java

### A. Factorial program in Java using while loop

One of the ways to calculate the factorial of a number in Java is by using a while loop. Here’s an example of how to do it:

```import java.util.Scanner;

public class FactorialExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
int fact = 1;
int i = 1;
while (i <= num) {
fact *= i;
i++;
}
System.out.println("Factorial of " + num + " is: " + fact);
}
}

```

Explanation of the code:

This Java code prompts the user to input a number and then calculates it’s factorial using a while loop. Here’s how it works:

1. The code starts by importing the Scanner class from the Java utility library.
2. We define the main method and create a Scanner object named ‘input’ to receive input from the user.
3. The user is prompted to enter a number through the “Enter a number:” message.
4. We store the number entered by the user in an integer variable named ‘num’.
5. Two more integer variables ‘fact’ and ‘i’ are initialized with 1 and 1, respectively.
6. We initiate a while loop with the condition that ‘i’ should be less than or equal to ‘num’.
7. Within the loop, the value of ‘fact’ is multiplied by the current value of ‘i’, and the updated value is stored back in ‘fact’.
8. We increment the value of ‘i’ by 1 after each iteration.
9. Once the while loop ends, the factorial of the entered number is stored in the ‘fact’ variable.
10. We display the final result on the console by printing the message “Factorial of (entered number) is: (factorial)”.

#### Output:

``````Enter a number: 5
Factorial of 5 is: 120``````

In this example, the user inputs 5 as the number, and the code calculates its factorial as 120, which is then displayed on the console.

A complete guide to IIT Bombay Spoken Tutorial, Here!

### B. Factorial program in Java without loop

Another way to calculate the factorial of a number in Java is by using recursion. Here’s an example of how to do it:

```import java.util.Scanner;

public class FactorialExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
int fact = factorial(num);
System.out.println("Factorial of " + num + " is: " + fact);
}
public static int factorial(int num) {
if (num == 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}
}

```

Explanation of the code:

In this program, we take input from the user and store it in the variable num. We then call the factorial() function and pass the value of num to it. The factorial() function is a recursive function that calculates the factorial of the given number by calling itself with a smaller value of num. The base case for the recursion is when num equals 0, in which case the function returns 1.

#### Output:

``````Enter a number: 5
Factorial of 5 is: 120

``````

### C. Factorial program in Java using recursion

Another way to calculate the factorial of a number in Java is by using a for loop. Here’s an example of how to do it:

```import java.util.Scanner;

public class FactorialExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial of " + num + " is: " + fact);
}
}

```

Explanation of the code:

In this program, we take input from the user and store it in the variable num. We then initialize the variable fact to 1. We use a for loop to calculate

Calculating the factorial of a number is a frequent programming task that programmers often encounter in mathematical applications. In this blog post, we will discuss how to write a factorial program in Java using two different approaches.

#### Output:

``````Enter a number: 5
Factorial of 5 is: 120

``````

### D. Factorial program in Java without loop

Here’s how you can write a factorial program in Java without using a loop:

```import java.util.Scanner;

public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int fact = 1;
for(int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial of " + num + " is " + fact);
}
}

```

Explanation of the code:

First, we import the Scanner class to read user input.

To obtain user input, we prompt the user to enter a number, which is then stored in the variable ‘num’.

We initialize a variable named “fact” with a value of 1, which we will utilize to store the factorial.

We then use a for loop to iterate from 1 to num and calculate the factorial by multiplying each number in the loop with the fact variable.

Finally, we print out the result.

#### Output:

``````Enter a number: 5
Factorial of 5 is: 120``````

Get a Complete list of Online Certification Courses in India here!

### E. Factorial program in Java while do loop

Here’s how you can write a factorial program in Java using a do-while loop:

```import java.util.Scanner;

public class FactorialProgram {

public static void main(String[] args) {
int num, factorial = 1, i = 1;
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to calculate its factorial: ");
num = scanner.nextInt();

do {
factorial *= i;
i++;
} while (i <= num);

System.out.println("Factorial of " + num + " is: " + factorial);
}
}

```

Explanation of the code:

First, we import the Scanner class to read user input.

To obtain user input, we prompt the user to enter a number, which is then stored in the variable ‘num’.

To store the factorial, we initialize a variable named “fact” with an initial value of 1.

Subsequently, we utilize a for loop to iterate from 1 to num, calculating the factorial by multiplying each number in the loop with the fact variable.

Finally, we print out the result.

#### Output:

If we run the program and enter the number 5, we should see the following output:

``````Enter a number to calculate its factorial: 5
Factorial of 5 is: 120
``````

This means that the factorial of 5 is 120, which is the correct result.

## 10 Tips and Tricks for Writing a Factorial Program in Java:

• Use a loop to calculate the factorial – this is the most efficient way to do it.
• Declare a variable to hold the result of the calculation.
• Initialize the result variable to 1, since the factorial of 0 is 1.
• Use a for loop to multiply the result variable by each integer from 1 to n.
• Check for special cases like n=0 or n=1 separately, since the loop won’t execute in those cases.
• Use a long data type for the result variable, since factorials can get very large very quickly.
• Handle negative input values appropriately – either throw an exception or return a special value like -1.
• Use recursion if you prefer a recursive solution – this is less efficient than using a loop but can be more elegant.
• Consider using BigInteger if you need to calculate factorials of very large numbers – this is also less efficient than using a loop but can handle arbitrarily large values.