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 factorial of a given number in java. 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 factorial of a given number in java by using 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 of a given number in java using a while loop. Here’s how it works:

- The code starts by importing the Scanner class from the Java utility library.
- We define the main method and create a Scanner object named ‘input’ to receive input from the user.
- The user is prompted to enter a number through the “Enter a number:” message.
- We store the number entered by the user in an integer variable named ‘num’.
- Two more integer variables ‘fact’ and ‘i’ are initialized with 1 and 1, respectively.
- We initiate a while loop with the condition that ‘i’ should be less than or equal to ‘num’.
- Within the loop, the value of ‘fact’ is multiplied by the current value of ‘i’, and the updated value is stored back in ‘fact’.
- We increment the value of ‘i’ by 1 after each iteration.
- Once the while loop ends, the factorial of the entered number is stored in the ‘fact’ variable.
- 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.
- Add comments to your code to explain what it’s doing, especially if you’re using a recursive solution.

Writing a factorial program in Java can be a great exercise for beginners to practice their programming skills. By following the tips and tricks outlined above, you can write an efficient and elegant program that calculates the factorial of any positive integer. Whether you choose to use a loop or recursion, it’s important to handle special cases like negative input values and very large input values. Additionally, adding comments to your code can make it easier for others to understand and modify in the future. Overall, writing a factorial program in Java can be a fun and rewarding experience for programmers of all skill levels.

We hope that our blog post on “Factorial program in Java” will effectively guide and inform you about your Java-related questions. To keep enhancing your coding skills, do check out **Newtum’s** website and explore our online coding courses covering Java, Python, PHP, and more.