Calculating the factorial of a number is a common exercise in programming that helps you understand loops and recursion. The factorial of a non-negative integer nnn is the product of all positive integers less than or equal to nnn. It is denoted by n!n!n!. For example, the factorial of 5 (denoted as 5!5!5!) is 5×4×3×2×1=1205 \times 4 \times 3 \times 2 \times 1 = 1205×4×3×2×1=120.
Java Program to Calculate Factorial
Let’s write a Java program to calculate the factorial of a number using both iterative and recursive methods.
Iterative Method
In the iterative method, we use a loop to multiply the numbers from 1 to nnn.
Write a Java program to calculate the factorial of a number.
Here’s the complete code:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a non-negative integer
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
// Check if the number is non-negative
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
// Calculate the factorial using the iterative method
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
// Print the factorial
System.out.println("The factorial of " + number + " is " + factorial);
}
}
}
Explanation of the Iterative Method
- Importing the Scanner Class: We import the
Scanner
class from thejava.util
package to read input from the user.
import java.util.Scanner;
2. Creating the Main Class: We create a public class named Factorial
.
public class Factorial {
3. Main Method: The main
method is the entry point of the program. Inside this method, we will write the code to calculate the factorial.
public static void main(String[] args) {
4. Creating a Scanner Object: We create a Scanner
object to read input from the user.
Scanner scanner = new Scanner(System.in);
Reading Input from the User: We prompt the user to enter a non-negative integer and store this value in a variable.
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
Checking for Non-Negative Input: We check if the number is non-negative. If the number is negative, we print an error message.
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
Calculating the Factorial Iteratively: We use a for
loop to calculate the factorial by multiplying the numbers from 1 to the input number.
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
Printing the Factorial: Finally, we print the calculated factorial.
System.out.println("The factorial of " + number + " is " + factorial);
Recursive Method
In the recursive method, we define a function that calls itself to multiply the numbers from nnn down to 1.
Here’s the complete code:
import java.util.Scanner;
public class FactorialRecursive {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a non-negative integer
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
// Check if the number is non-negative
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
// Calculate the factorial using the recursive method
long factorial = factorial(number);
// Print the factorial
System.out.println("The factorial of " + number + " is " + factorial);
}
}
// Recursive method to calculate factorial
public static long factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! = 1
} else {
return n * factorial(n - 1); // Recursive case
}
}
}
Explanation of the Recursive Method
- Importing the Scanner Class: We import the
Scanner
class from thejava.util
package to read input from the user.
import java.util.Scanner;
Creating the Main Class: We create a public class named FactorialRecursive
.
public class FactorialRecursive {
Main Method: The main
method is the entry point of the program. Inside this method, we will write the code to calculate the factorial using recursion.
public static void main(String[] args) {
Creating a Scanner Object: We create a Scanner
object to read input from the user.
Scanner scanner = new Scanner(System.in);
Reading Input from the User: We prompt the user to enter a non-negative integer and store this value in a variable.
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
Checking for Non-Negative Input: We check if the number is non-negative. If the number is negative, we print an error message.
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
Calculating the Factorial Recursively: We call the factorial
method to calculate the factorial.
long factorial = factorial(number);
Recursive Method: The factorial
method is defined to call itself with the argument n-1
until it reaches the base case n == 0
.
public static long factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! = 1
} else {
return n * factorial(n - 1); // Recursive case
}
}
Printing the Factorial: Finally, we print the calculated factorial.
System.out.println("The factorial of " + number + " is " + factorial);
Running the Program
To run either program, follow these steps:
- Save the code in a file named
Factorial.java
orFactorialRecursive.java
. - Open a command prompt or terminal and navigate to the directory where you saved the file.
- Compile the program using the following command:
javac Factorial.java
or
javac FactorialRecursive.java
Run the compiled program using the following command:
java Factorial
OR
java FactorialRecursive
- Follow the prompt to enter a non-negative integer. The program will display the factorial of the entered number.
Top 100 Java Programs: Click Here
What did we learn from this article?
Calculating the factorial of a number is a fundamental exercise that helps in understanding loops and recursion in programming. The iterative method uses a loop to multiply numbers, while the recursive method calls a function repeatedly until it reaches the base case. Both methods are essential for learning different approaches to solving problems in Java. By practicing these techniques, you can strengthen your problem-solving skills and gain confidence in your ability to write efficient Java code.