Java Reference
In-Depth Information
Once the base case is reached, the suspended executions resume, beginning with the most recent.
Thus,
sumOf(2)
returns 1
+
2, or 3; then
sumOf(3)
returns 3
+
3, or 6. Figure 7-5 illustrates this
computation.
Question 4
Write a recursive valued method that computes the product of the integers
from 1 to
n
, where
n
>
0.
Note:
Should you trace a recursive method?
We have shown you how to trace the execution of a recursive method primarily to show you how
recursion works and to give you some insight into how a typical compiler implements recursion.
Should you ever trace a recursive method? Usually no. You certainly should not trace a recursive
method while you are writing it. If the method is incomplete, your trace will be, too, and you are
likely to become confused. If a recursive method does not work, follow the suggestions given in
the next programming tip. You should trace a recursive method only as a last resort.
FIGURE 7-5
Tracing the execution of
sumOf(3)
(a)
(b)
(c)
sumOf(1):
return
1;
sumOf(2):
return
sumOf(1) + 2;
sumOf(2):
return
sumOf(1) + 2;
sumOf(3):
return
sumOf(2) + 3;
sumOf(3):
return
sumOf(2) + 3;
sumOf(3):
return
sumOf(2) + 3;
(d)
(e)
(f)
6 is displayed
sumOf(2):
return
1 + 2 = 3;
sumOf(3):
return
3 + 3 = 6;
sumOf(3):
return
sumOf(2) + 3;