Java Reference
In-Depth Information
EXAMPLE:
(continued)
so the final value returned for
is
. So, the following would set the value
power(2,
1)
2
of
equal to
:
result4
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
is calculated as follows:
power(2, 3)
is
power(2, 3)
power(2, 2)*2
power(2, 2)
is
power(2, 1)*2
is
power(2, 1)
power(2, 0)*2
power(2, 0)
is
(
)
1
stopping case
When the computer reaches the stopping case,
, 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,
0)
. 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,
1)
. The details
power(2,
3)
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
{
11
if (n < 0)
12
{
13
System.out.println("Illegal argument to power.");
14
System.exit(0);
15
}
Search WWH ::




Custom Search