Java Reference
In-Depth Information
6. public static void doubleReverse(String s) {
if (s.length() > 0) {
char last = s.charAt(s.length() - 1);
System.out.print(last);
System.out.print(last);
doubleReverse(s.substring(0, s.length() - 1));
}
}
7. A call stack is the structure of information about all methods that have currently
been called by your program. Recursion produces a tall call stack in which each
recursive call is represented.
8. The new code would print the lines in their original order, not reversed.
9. The new code would cause infinite recursion because each recursive call just
makes another recursive call and doesn't progress toward the base case.
10. The second version of the pow method is more efficient than the first because it
requires fewer recursive calls. Both versions are recursive.
11. (a) 6
(b) 4
(c) 7
(d) 0
(e) 1
12. (a) 57
(b) 1029
(c) -74
(d) 2438
(e) 132483
13. public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
14. The base case if statement has a bug: It should test for numbers less than 10, not
greater. The following line is correct:
if (n < 10) {
15. When the parameters needed for recursion don't match the ones that make sense for
the client to pass, use a public method with the signature that is desired by the client
and a private helper method with the signature that is needed for the recursion.
Search WWH ::




Custom Search