Question: A. Consider the square() method shown below that takes a non-negative int argument. Complete the code for the square() method so that it correctly calls
A. Consider the square() method shown below that takes a non-negative int argument. Complete the code for the square() method so that it correctly calls the squareHelper() method to produce the square of n.
public int square(int n) { ____________________; } public int squareHelper(int c, int n) { if (c == 1) { return n; } else { return n + squareHelper(c - 1, n); } } | 1. | return squareHelper(n, n - 1) |
| 3. | return squareHelper(n, n) |
| 4. | return squareHelper(n - 1, n) |
B. Consider the permutations() method from the textbook, which is intended to return all permutations of the word passed in as a parameter. How does the permutations() method simplify its input for the recursive call?
public static ArrayList permutations(String word) { ArrayList result = new ArrayList(); if (word.length() == 0) { result.add(word); return result; } else { for (int i = 0; i < word.length(); i++) // line #4 { String shorter = word.substring(0, i) + word(substring(i + 1)); ArrayList shorterPermutations = permutations(shorter); for (String s : shorterPermutations) { result.add(word.charAt(i) + s); } } return result; } }
| 1. | It finds permutations of a shorter word by removing the last character. |
| 2. | It finds permutations of a shorter word by removing both the first and last character. |
| 3. | It finds permutations of a shorter word by removing the first character. |
| 4. | It finds permutations of shorter words formed by removing the ith character. |
C. Consider the getArea() method from the textbook shown below.
public int getArea() { if (width <= 0) // line #1 { return 0; // line #2 } else if (width == 1) // line #3 { return 1; // line #4 } else { Triangle smallerTriangle = new Triangle(width - 1); // line #5 int smallerArea = smallerTriangle.getArea(); // line #6 return smallerArea + width; // line #7 } } Where is/are the recursive call(s)?
D. Consider the helper method reversePrint, which uses recursion to display in reverse the elements in a section of an array limited by the firstIndex and lastIndexarguments. What statement should be used to complete the recursive method?
public static void reversePrint(int[] array, int firstIndex, int lastIndex) { if (firstIndex < lastIndex) { reversePrint(array, firstIndex + 1, lastIndex); } System.out.println(_________________); } public static void main(String[] args) { int [] numbers = { 4, 7, 1, 0, 2, 7 }; reversePrint(numbers, 0, numbers.length - 1); }