Java Program to Calculate Factorial Using Iterative and Recursive Methods

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Write a Java Program to find the factorial of a given number.

Answer:

Certainly! Below is a simple Java program that calculates the factorial of a given number using both iterative and recursive methods. You can choose either method based on your preference.

import java.util.Scanner;

public class FactorialCalculator {

    // Iterative method to calculate factorial
    public static long factorialIterative(int n) {
        long result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    // Recursive method to calculate factorial
    public static long factorialRecursive(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }
        return n * factorialRecursive(n - 1);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a non-negative integer: ");
        int number = scanner.nextInt();

        if (number < 0) {
            System.out.println("Factorial is not defined for negative numbers.");
        } else {
            // Calculate factorial using iterative method
            long iterativeResult = factorialIterative(number);
            System.out.println("Factorial of " + number + " (Iterative): " + iterativeResult);

            // Calculate factorial using recursive method
            long recursiveResult = factorialRecursive(number);
            System.out.println("Factorial of " + number + " (Recursive): " + recursiveResult);
        }

        scanner.close();
    }
}

Explanation:

  1. Imports: The program imports the Scanner class for user input.
  2. Factorial Methods:
    • factorialIterative(int n): This method calculates the factorial using a loop.
    • factorialRecursive(int n): This method calculates the factorial using recursion.
  3. Main Method:
    • It prompts the user to enter a non-negative integer.
    • It checks if the number is negative and prints an error message if so.
    • It calculates the factorial using both methods and prints the results.

How to Run:

  1. Copy the code into a file named FactorialCalculator.java.
  2. Compile the program using javac FactorialCalculator.java.
  3. Run the program using java FactorialCalculator.
  4. Enter a non-negative integer when prompted to see the factorial calculated using both methods.