Chapter 6 Methods (1 on 1 web hosting) 279 A recursive definition of
Chapter 6 Methods 279 A recursive definition of the factorial method is arrived at by observing the following relationship: n! = n (n -1)! For example, 5! is clearly equal to 5 * 4!, as is shown by the following equations: 5!= 5 4 3 2 1 5! = 5 (4 3 2 1) 5! = 5 (4!) The evaluation of 5! would proceed as shown in Fig. 6.11. Figure 6.11 (a) shows how the succession of recursive calls proceeds until 1! is evaluated to be 1, which terminates the recursion. Figure 6.11 (b) shows the values returned from each recursive call to its caller until the final value is calculated and returned. Figure 6.12 uses recursion to calculate and print the factorials of the integers from 0 to 10. (The choice of the data type long will be explained momentarily.) The recursive method factorial(lines 29 39) first tests to determine whether a terminating condition (line 32) is true. If numberis less than or equal to 1(the base case), factorialreturns 1, no further recursion is necessary and the method returns. If numberis greater than 1, line 37 expresses the problem as the product of number and a recursive call to factorialevaluating the factorial of number-1. Note that factorial(number-1)is a slightly simpler problem than the original calculation factorial(number). 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 Final value = 120 5! = 5 * 24 = 120 is returned 4! = 4 * 6 = 24 is returned 2! = 2 * 1 = 2 is returned 3! = 3 * 2 = 6 is returned 1 returned (a) Procession of recursive calls. (b) Values returned from each recursive call. Fig. 6.11 Recursive evaluation of 5!. 1 // Fig. 6.12: FactorialTest.java 2 // Recursive factorial method 3 4 // Java core packages 5 import java.awt.*; 6 Fig. 6.12Calculating factorials with a recursive method (part 1 of 2). Fig. 6.12 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01