Java Reference
In-Depth Information
EXAMPLE:
(continued)
power(2, 0)
with its value of
1
and resumes the suspended computation. The resumed
computation determines the final value for
power(2, 1)
from the above
return
statement as
Power(2, 0)*2
is
1*2 which is 2
so the final value returned for
power(2, 1)
is
2
. So, the following would set the
value of
result4
equal to
2
:
int
result4 = power(2, 1);
Larger numbers for the second argument will produce longer chains of recursive calls.
For example, consider the statement
System.out.println(power(2, 3));
The value of
power(2, 3)
is calculated as follows:
power(2, 3)
is
power(2, 2)*2
power(2, 2)
is
power(2, 1)*2
power(2, 1)
is
power(2, 0)*2
power(2, 0)
is
1 (stopping case)
When the computer reaches the stopping case,
power(2, 0)
, there are three suspended
computations. After calculating the value returned for the stopping case, it resumes the
most recently suspended computations to determine the value of
power(2, 1)
. After
that, the computer completes each of the other suspended computations, using each
value computed as a value to plug into another suspended computation, until it reaches
and completes the computation for the original call
power(2, 3)
. The details of the
entire computation are illustrated in Display 11.4.
Display 11.3
The Recursive Method
power
(part 1 of 2)
1
public class
RecursionDemo2
2 {
3
public static void
main(String[] args)
4 {
5
for
(
int
n = 0; n < 4; n++)
6 System.out.println("3 to the power " + n
7 + " is " + power(3, n));
8 }
9
public static int
power(int x, int n)
10 {