English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive List of Java Examples
In this program, you will learn how to use recursive functions in Java to find and display the factorial of a number.
The factorial of a positive number n is given by the following formula:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
The factorial of a negative number does not exist. The factorial of 0 is1.
In this example, you will learn how to use recursion to find the factorial of a number. Visit this page to learn howUsing a loop to find the factorial of a number.
public class Factorial { public static void main(String[] args) { int num = 6; long factorial = multiplyNumbers(num); System.out.println("") + num + "Factorial = " + factorial); } public static long multiplyNumbers(int num) { if (num >= 1) return num * multiplyNumbers(num - 1); else return 1; } }
When the program is run, the output is:
6Factorial = 720
Initially, multiplyNumbers() is called from the main() function, with6Passed as a parameter.
Because6Greater than or equal to1, so6Multiplied by the result of multiplyNumbers(), which passed5 (num -1). Because it is called from the same function, it is a recursive call.
In each recursive call, the value of the parameter num is reduced1Until num is less than1.
When the value num is less than1There will be no recursive calls.
Each recursive call returns to us:
6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720