Page 819 - Introduction to Programming with Java: A Problem Solving Approach
P. 819
Appendix 8 Recursion 785 works. The way to make this problem simpler is to reduce the value of n, and the stopping condition is when
n 1. At that point, n! 1. For any other value of n, we have the relationship: n! = n * (n-1)!
This formula is the recursive relationship in the calculation of a factorial.
Figure A8.1 contains a Java implementation of the recursive calculation of a factorial. The recursive
method, factorial, is an “if-else” statement. The if condition is the stopping condition, and the else body includes a recursive method call, in which the method calls itself. When factorial is first called from main, its parameter value is 5, so the stopping condition is not satisfied, and the method calls itself from within the else body with the argument value 5 minus 1, which equals 4. This recursive method calling continues until the method parameter equals 1. At that point, the method returns 1 to the previous
11
{
12
System.out.println(factorial(5));
} // end main
13
14
15
//************************************************
16
17
private static int factorial(int n)
18
{
19
int nF; // n factorial
if (n == 1) // stopping condition
{
20
21
22
23
nF = 1;
24
}
1 /***************************************************
2 *
3 *
4*
5
Factorial.java
Dean & Dean
This program computes the factorial of an integer.
***************************************************/
6
7
8
public class Factorial
9{
10
Apago PDF Enhancer
public static void main(String[] args)
*
25
else
recursive method call
26
{
27
nF = n * factorial(n-1);
28
}
return nF;
29
workonreturnedvalue
30
}
// end factorial
40 }
Output:
120
// end Factorial class
Figure A8.1 Use of recursion to calculate the factorial of an integer