Methods
Java Program to Find Factorial Using Recursion
A Java program to find the factorial of a number using recursion.
Problem Description
Write a Java program to find the factorial of a non-negative integer using recursion.
Code
public class FactorialRecursion {
public static void main(String[] args) {
int num = 6;
long factorial = multiplyNumbers(num);
System.out.println("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num) {
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}Output
Factorial of 6 = 720Explanation
- Recursion:
multiplyNumberscalls itself. - Base Case: When
numis less than 1, return 1. - Logic:
n! = n * (n-1)!.
