Java Reference
In-Depth Information
6. Convert the following iterative method into a recursive method:
// Prints each character of the string reversed twice.
// doubleReverse("hello") prints oolllleehh
public static void doubleReverse(String s) {
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
System.out.print(s.charAt(i));
}
}
Section 12.2: A Better Example of Recursion
7. What is a call stack, and how does it relate to recursion?
8. What would be the effect if the code for the reverse method were changed to the following?
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
// recursive case (nonempty file)
String line = input.nextLine();
System.out.println(line); // swapped order
reverse(input); // swapped order
}
}
9. What would be the effect if the code for the reverse method were changed to the following?
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
// recursive case (nonempty file)
reverse(input); // moved this line
String line = input.nextLine();
System.out.println(line);
}
}
Section 12.3: Recursive Functions and Data
10. What are the differences between the two versions of the pow method shown in Section 12.3? What advantage does
the second version have over the first version? Are both versions recursive?
11. Consider the following method:
public static int mystery4(int x, int y) {
if (x < y) {
return x;
} else {
Search WWH ::




Custom Search