Java Reference
In-Depth Information
General Form for a Recursive Method That Returns a Value
The recursive methods you have seen thus far are all
void
methods, but recursion is
not limited to these methods. A recursive method can return a value of any type. The
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
definition 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 is 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
stopping
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
, that 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
double
. Display 11.3 contains a recursive definition for a static method that is
similar to
pow
, 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
, because
2
3
is
8
:
int
result2 = power(2, 3);
Outside the defining class, this would be written as
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