Java Reference
In-Depth Information
18.6
Fill in the blanks in each of the following statements:
a)
The ratio of successive Fibonacci numbers converges on a constant value of 1.618…, a
number that has been called the
or the
.
b)
Iteration normally uses a repetition statement, whereas recursion normally uses a(n)
statement.
c)
Fractals have a(n)
property—when subdivided into parts, each is a reduced-
size copy of the whole.
Answers to Self-Review Exercises
18.1
a) False. A method that calls itself in this manner is an example of indirect recursion.
b) False. Recursion can be inefficient in computation because of multiple method calls and memo-
ry-space usage. c) True. d) False. To make recursion feasible, the recursion step in a recursive solu-
tion must resemble the original problem, but be a slightly
smaller
version of it.
18.2
d
18.3
a
18.4
c
18.5
b
18.6
a) golden ratio, golden mean. b) selection. c) self-similar.
Exercises
18.7
What does the following code do?
1
public int
mystery(
int
a,
int
b)
2
{
3
if
(b ==
1
)
4
return
a;
5
else
6
return
a + mystery(a, b -
1
);
7
}
18.8
Find the error(s) in the following recursive method, and explain how to correct it (them).
This method should find the sum of the values from 0 to
n
.
1
public int
sum(
int
n)
2
{
3
if
(n ==
0
)
4
return
0
;
5
else
6
return
n + sum(n);
7
}
18.9
(Recursive
power
Method)
Write a recursive method
power(base,
exponent)
that, when
called, returns
base
exponent
For example,
power
(3,4)
= 3 * 3 * 3 * 3. Assume that
exponent
is an integer greater than or equal
to 1.
Hint:
The recursion step should use the relationship