In this Java program, you’ll learn how to find the factorial of a number using a recursion function. In this program, we used the following Java basics such as if...else
conditions, and java recursion methods.
In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n:
n!=(n-1)x(n-2)x(n-3)x…3x2x1
The factorial, symbolized by an exclamation mark (!), is a quantity defined for all integers greater than or equal to 0.
For example,
5!=5x4x3x2x1=120
6!=6x5x4x3x2x1=720
The value of 0! is 1.
Here is the code of the program to print factorial of a number using Recursion:
//Java Program to Find Factorial of a Number Using Recursion
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int number;
// create an object of Scanner class
Scanner sc = new Scanner(System.in);
// ask users to enter numbers
System.out.println("Enter a number: ");
number = sc.nextInt();
long factorial = factorial(number);
System.out.println("Factorial of " + number + " = " + factorial);
sc.close();
}
public static long factorial(int num) {
if (num >= 1)
return num * factorial(num - 1);
else
return 1;
}
}
Enter a number:
5
Factorial of 5 = 120
number
.factorial()
is a recursive function that is called from the main()
function and we take 5 as input and pass it as an argument.factorial()
where 4 (num -1
) is passed. Since it is called from the same function, it is known as a recursive call.num
is decreased by 1 until num
reaches less than 1.num
is less than 1, there is no recursive call.
Comments