1. Introduction
Factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. For example, 5! = 5*4*3*2*1 = 120. A Java program can easily calculate the factorial of a number using a for loop or recursion. This is a common exercise to learn loops, conditionals, and recursion in Java.
2. Program Steps
1. Import the Scanner class from the java.util package for user input.
2. Define the main class named FactorialCalculator.
3. Inside the main class, define the main method.
4. Inside the main method, create an object of the Scanner class to take user input.
5. Prompt the user to enter a non-negative integer for which the factorial will be calculated.
6. Initialize a variable to store the result and set its initial value to 1.
7. Use a for loop to calculate the factorial of the given number.
8. Print the calculated factorial of the given number.
3. Code Program
import java.util.Scanner; // 1. Importing Scanner class for user input
public class FactorialCalculator { // 2. Defining the main class
public static void main(String[] args) { // 3. Defining the main method
Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input
System.out.print("Enter a non-negative integer: "); // 5. Prompting user for a non-negative integer
int num = input.nextInt(); // Storing the user input in variable num
long factorial = 1; // 6. Initializing the result variable with 1
// 7. Calculating the factorial of the given number using a for loop
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("The factorial of " + num + " is: " + factorial); // 8. Printing the calculated factorial
input.close(); // Closing the Scanner object to avoid memory leak
}
}
Output:
Enter a non-negative integer: 5 The factorial of 5 is: 120
4. Step By Step Explanation
– Step 1: The Scanner class from java.util package is imported for taking user input.
– Step 2: The main class named FactorialCalculator is defined.
– Step 3: The main method is defined inside the main class. It’s the entry point of our program.
– Step 4: A Scanner object named "input" is created for user input.
– Step 5: The user is prompted to enter a non-negative integer, and the value 5 is stored in the variable num.
– Step 6: A variable named factorial is initialized to 1 to store the result.
– Step 7: A for loop is used to calculate the factorial of 5.
– Step 8: The program prints out the calculated factorial, which is 120.
– Lastly, the Scanner object is closed to avoid any potential memory leak.