Factorial Program Using Loop in Java

9/3/2021

#Factorial Program Using Loop in Java

Go Back

Factorial Program Using Loop in Java

Factorial is a mathematical operation where a number is multiplied by all its preceding positive integers. It is denoted by n! and is calculated as follows:

Examples:

  • 4! = 4 × 3 × 2 × 1 = 24
  • 5! = 5 × 4 × 3 × 2 × 1 = 120

In this article, we will discuss how to calculate the factorial of a number using loops and recursion in Java.

#Factorial Program Using Loop in Java

Factorial Program Using Loop in Java

A loop-based approach iterates through all numbers up to the given number and multiplies them together to compute the factorial.

Example 1: Factorial Without Recursion (Using Loop)

class FactorialExample {
    public static void main(String args[]) {
        int i, fact = 1;
        int number = 5; // Number for factorial calculation  
        
        for (i = 1; i <= number; i++) {
            fact = fact * i;
        }
        
        System.out.println("Factorial of " + number + " is: " + fact);
    }
}

Explanation:

  • We initialize fact = 1.
  • We iterate from 1 to n and multiply fact by the loop variable.
  • The final value of fact gives the factorial of the number.

Factorial Program Using Recursion in Java

A recursive approach solves the problem by calling the function repeatedly with a decremented value of n until n = 1.

Example 2: Factorial Using Recursion

public class FactorialRecursion {
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1; // Base case
        } else {
            return n * factorial(n - 1); // Recursive call
        }
    }
    
    public static void main(String[] args) {
        int number = 5;
        System.out.println("Factorial of " + number + " is: " + factorial(number));
    }
}

Explanation:

  • The function calls itself with n-1 until it reaches n=1.
  • The recursion builds a call stack and returns the final product.
  • This approach is more concise but may cause stack overflow for large values of n.

Conclusion

  • Loop-based approach is efficient and does not consume additional stack memory.
  • Recursive approach is elegant but can lead to stack overflow for large numbers.

Both methods are useful in different scenarios. Choose the best approach based on performance and readability.

More Learning Resources

If you found this article helpful, follow us for more updates on: 📌 Instagram | 📌 LinkedIn | 📌 Facebook | 📌 Twitter

This article is contributed by the Developer Indian Team. If you find any mistakes or have suggestions, feel free to share your feedback!


 

Table of content