Using Recursion in Java Find Factorial of Number

By | July 2, 2019

Task: Write a program Using Recursion in Java Find Factorial of Number.

The source code of Java program to find factorial of a given number using recursion is:

/*
 Write a Java program to calculate 
 factorial of a number. Use a recursive method.
 */
package recursivefactorial;
/**
 * @author www.EasyCodeBook.com
 */
import java.util.Scanner;
public class RecursiveFactorial {
    public static int factorial(int n)
    {
        if ( n == 0)
            return 1;
        else
            return n * factorial(n-1);
    }
    public static void main(String[] args) {
    
        int number;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number:");
        number = input.nextInt();
        System.out.println("Factorial of "+number+" is "+factorial(number));
            
    }
}

The sample run and output of Recursive Factorial Method in Program is:

Enter a number:5
Factorial of 5 is 120

Write a program Using Recursion in Java Find Factorial of Number

Write a program Using Recursion in Java Find Factorial of Number

The process of recursion in Java

to calculate factorial of 3 is shown in the following table:

Recursion in Java factorial program

Recursion in Java factorial program

One thought on “Using Recursion in Java Find Factorial of Number

  1. Pingback: Recursion in Java Explained With Examples » EasyCodeBook.com

Leave a Reply

Your email address will not be published. Required fields are marked *