Home / Data structures and Algorithms by Java Examples / Recursion / Factorial Program using Recursion in JAVA Example
Factorial Program using Recursion in JAVA Example
2493 views.
FactorialRecursion.java
class FactorialRecursion {
    
    public static int factorial(int n) {
        //base case: return 1 (n = 1).
        if (n == 1) {
            return 1;
        }
        else {
            //recursive case: call n * factorial(n-1).
            //5 * 4 * 3 * 2 * 1
            return n * factorial(n-1);
        }
    }
    
    public static void main(String[] args) {
        int n = 5;
        
        //Finding factorial and stores into f variable.
        int f = factorial(n);
        System.out.println(n+"! = "+f);
    }
}
Output
5! = 120
Related Examples
   Simple Recursion Example in JAVA
   Print array using recursion JAVA Example
   Recursion on ArrayList Strings in JAVA Example
   Factorial Program using Recursion in JAVA Example
   Fibonacci Series using Recursion in JAVA Example
   Tree Traversal with Recursion in JAVA Example
   Tree Traversal without Recursion Using Stack Class in JAVA Example
   Is ArrayList Ordered using Recursion in JAVA Example
   Tower of Hanoi using Recursion in Java Example
Copyright © 2016 Learn by Examples, All rights reserved