Google News
logo
Java Program to find factorial of a given Number using Recursion
In the following example of Java program to find the factorial of a given number using recursion :
Program :
public class Factorial {

    public static void main(String[] args) {
        int num = 5;
        int factorial = findFactorial(num);
        System.out.println("Factorial of " + num + " is " + factorial);
    }

    public static int findFactorial(int num) {
        if (num == 0) {
            return 1;
        } else {
            return num * findFactorial(num - 1);
        }
    }
}
Output :
Factorial of 5 is 120
In this program, we first declare an integer variable num and initialize it with the value 5. We then call the findFactorial method, passing in num, and store the returned value in the factorial variable. Finally, we print the factorial of the given number using a formatted string.

The findFactorial method is defined as a static method that takes an integer parameter num and returns an integer. The method uses recursion to find the factorial of the given number. If the number is 0, it simply returns 1, since the factorial of 0 is 1. Otherwise, it multiplies the number with the factorial of the number minus 1, effectively reducing the number by 1 with each recursive call.