CH 7 AP Textbook Recursion MCQs 9th
CH 7 AP Textbook Recursion MCQs 9th
RECURSION
(A) I only
(B) III only
(C) I and II only
(D) I and III only
(E) II and III only
II if (n == 1)
return 1;
else
return n + sum(n - 1);
III if (n == 1)
return 1;
else
return sum(n) + sum(n - 1);
(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I, II, and III
8. Refer to method f.
public int f(int k, int n)
{
if (n == k)
return k;
else
if (n > k)
return f(k, n - k);
else
return f(k - n, n);
}
10. Which best describes what the printString method below does?
public void printString(String s)
{
if (s.length() > 0)
{
printString(s.substring(1));
System.out.print(s.substring(0, 1));
}
}
13. A user enters several positive integers at the keyboard and terminates
the list with a sentinel (-999). A writeEven method reads those
integers and outputs the even integers only, in the reverse order that
they are read. Thus, if the user enters
3 5 14 6 1 8 -999
Assume that the user enters at least one positive integer and terminates
the list with −999. Here is the method.
/** Postcondition: All even integers in the list are output
in
* reverse order.
*/
public static void writeEven()
{
int num = ...; //read user input
if (num != -999)
{
/* code */
}
}
I
if (num % 2 == 0)
System.out.print(num + " ");
writeEven();
II
if (num % 2 == 0)
writeEven();
System.out.print(num + " ");
III
writeEven();
if (num 2 % == 0)
System.out.print(num + " ");
(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I, II, and III
16. For the method call t(6), how many calls to t will be made, including
the original call?
(A) 6
(B) 7
(C) 11
(D) 15
(E) 25
17. This question refers to methods f1 and f2 that are in the same class.
public int f1(int a, int b)
{
if (a == b)
return b;
else
return a + f2(a - 1, b);
}
(A) (15!)/(2!)
(B) 3! + 4!
(C) (7!)!
(D) (3! + 4!)!
(E) 15
20. Which change in the code of the given methods will cause method
writeWithCommas to work as intended?
(A) Interchange the lines System.out.print(n / 100) and
System.out.print(n % 10) in method writeThreeDigits.
(B) Interchange the lines writeThreeDigits(n % 1000) and
writeWithCommas(n / 1000) in method writeWithCommas.
(C) Change the test in writeWithCommas to if (n > 1000).
(D) In the method writeWithCommas, change the line
writeThreeDigits(n % 1000) to writeThreeDigits(n / 1000).
(E) In the method writeWithCommas, change the recursive call
writeWithCommas(n / 1000) to writeWithCommas(n % 1000).
Assume that the screen looks like a Cartesian coordinate system with the
origin at the center, and that drawLine connects (x1,y1) to (x2,y2). Assume
also that x1, y1, x2, and y2 are never too large or too small to cause errors.
Which picture best represents the sketch drawn by the method call
sketch(a, 0, -a, 0, 2)