In this example, we will calculate the factorial of a number taking the value from the user.
You can also learn to find the Factorial of a Number in Java Using for loop.
Recursion refers to the function calling itself inside its function in a program.
Before we begin, you should have the knowledge of the following:
Factorial of n number: Factorial of n number is the product of all the positive descending integers and is denoted by n!.
Example:
factorial of n (n!) = n * (n-1) * (n-2) * (n-3)….1
factorial of 5 (n!) = 5 * 4 * 3 * 2 * 1
NOTE: Factorial of 0 (0!) = 1
Factorial Program using Recursion in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | //find the factorial of a number using recursion in java import java.util.Scanner; public class FactorialRecursion { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number: "); int num = scanner.nextInt(); //Called the user defined function fact int factorial = fact(num); System.out.println("Factorial of entered number is: " + factorial); } //function static int fact(int n) { int output; if (n == 1) { return 1; } output = fact(n - 1) *n; //recursion return output; } } |
Output:
Enter the number: 4
Factorial of entered number is: 24