Java Reference
In-Depth Information
technique for designing recursive methods that return a value is basically the same as
what you learned for
void
methods. An outline for a successful recursive method defi-
nition that returns a value is as follows:
•
One or more cases in which the value returned is computed in terms of calls to the
same method (that is, using recursive calls). As was the case with
void
methods, the
arguments for the recursive calls should intuitively be “smaller.”
•
One or more cases in which the value returned is computed without the use of any
recursive calls. These cases without any recursive calls are called
base cases
or
stop-
ping cases
(just as they were with
void
methods).
This technique is illustrated in the next Programming Example.
EXAMPLE:
Another Powers Method
In Chapter 5 we introduced the static method
pow
of the class
Math
. This method
pow
computes powers. For example,
Math.pow(2.0,3.0)
returns
2.0
3.0
, so the following
sets the variable
result
equal to
8.0
:
double
result = Math.pow(2.0, 3.0);
The method
pow
takes two arguments of type
double
and returns a value of type
dou-
ble
. Display 11.3 contains a recursive definition for a static method that is similar but
that works with the type
int
rather than
double
. This new method is called
power
. For
example, the following will set the value of
result2
equal to
8
, since
2
3
is
8
:
int
result2 = power(2, 3);
Outside the defining class, this would be written
int
result2 = RecursionDemo2.power(2, 3);
Our main reason for defining the method
power
is to have a simple example of a recursive
method, but there are situations in which the method
power
would be preferable to the
method
pow
. The method
pow
returns a value of type
double
, which is only an approximate
quantity. The method
power
returns a value of type
int
, which is an exact quantity. In
some situations, you might need the additional accuracy provided by the method
power
.
The definition of the method
power
is based on the following formula:
x
n
is equal to
x
n−1
* x
Translating this formula into Java says that the value returned by
power(x,
n)
should
be the same as the value of the expression
power(x, n
−
1)*x