Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Gaddis: Starting Out with Java: From Control Structures through Data Structures, 2/e © 2012 Pearson Education Answers to Review Questions Chapter 15 Multiple Choice and True/False 1. b 2. a 3. d 4. c 5. d 6. a 7. True 8. False 9. False 10. False Find the Error 1. The recursive method, myMethod, has no base case. So, it has no way of stopping. Algorithm Workbench 1. public static void main(String [] args) { String str = "test string"; display(str, 0); } public static void display(String str, int pos) { if (pos < str.length()) { System.out.print(str.charAt(pos)); display(str, pos + 1); } } 2. public static void main(String [] args) { String str = "test string"; display(str, str.length()-1); } 1 Gaddis: Starting Out with Java: From Control Structures through Data Structures, 2/e © 2012 Pearson Education 3. public static void display(String str, int pos) { if (pos >= 0) { System.out.print(str.charAt(pos)); display(str, pos - 1); } } 10 4. 0 1 2 3 4 5 6 7 8 9 10 5. 55 6. public static void sign(int n) { if (n > 0) { System.out.println("No Parking"); sign(n - 1); } } 7. public static int factorial(int num) { int fac = 1; for (int i = 1; i <=num; { fac = fac * i; } return fac; } i++) 2 Gaddis: Starting Out with Java: From Control Structures through Data Structures, 2/e © 2012 Pearson Education 3 Short Answer 1. An iterative algorithm uses a loop to solve the problem, while a recursive algorithm uses a method that calls itself. 2. What is a recursive algorithm's base case? What is the recursive case? The base case is a case in which the problem can be solved without recursion. A recursion case uses recursion to solve the problem, and always reduces the problem to a smaller version of the original problem. 3. For question 3 the base case is reached when arg is equal to 10. For question 4 the base case is also reached when arg is equal to 10. For question 5 the base case is reached when num is less-than or equal to 0. 4. Indirect recursion, because it involves multiple methods being called. 5. Recursive algorithms are usually less efficient than iterative algorithms. This is because a method call requires several actions to be performed by the JVM, such as allocating memory for parameters and local variables, and storing the address of the program location where control returns after the method terminates. 6. By reducing the problem with each recursive call, the base case will eventually be reached and the recursion will stop. 7. The value of an argument is usually reduced.