printable version
Quiz 3 Review B
[1]
[2]
[3]
[4]
[5]
[6]
[7]
Problem Q3rB.1.
Define the term base case as it applies to recursive
methods. Why is a base case necessary?
The base case is a situation in which a recursive method does
not perform any recursive invocations.
Without any base case, a recursive method will
recurse indefinitely, until the program runs out of memory,
whereupon it will abort.
Problem Q3rB.2.
If the below method is invoked as doStuff(64, 40), what
does the method display?
public void doStuff(int m, int n) {
if(n > 0) {
doStuff(n, m % n);
println(n);
}
}
Problem Q3rB.3.
If the below method is invoked as printStuff(4), what
does the method display?
public void printStuff(int n) {
if(n > 0) {
printStuff(n - 1);
println(n);
printStuff(n - 2);
}
}
Problem Q3rB.4.
Using no loops (i.e., using recursion), add a method
countDown that displays all the integers from its
parameter down to 0 (and including 0). The result should be that
the below program displays the integers from 10 down to and
including 0.
import acm.program.Program;
public class Blastoff extends Program {
public void run() {
countDown(10);
}
public void countDown(int n) {
println(n);
if(n > 0) countDown(n - 1);
}
}
Problem Q3rB.5.
Without using loops (i.e., by using recursion),
complete the following method so that it computes the nth harmonic
number. (Recall that the nth harmonic number is the sum of the
reciprocals of the integers from 1 to n; for example, the 3rd
harmonic number is
1/1 + 1/2 + 1/3 = 1.8333….)
public class Problem extends Program {
public double harm(int n) {
if(n == 1) {
return 1.0;
} else {
return 1.0 / n + harm(n - 1);
}
}
}
Problem Q3rB.6.
Without using loops (i.e., by using recursion), write a method
halvings that takes an integer parameter and returns the
number of times that integer can be halved before reaching 1
(rounding down for odd integers).
For example, halvings(10) should return 3, since the
sequence would be
10 → 5 → 2 → 1,
which involves three halvings.
public int halvings(int n) {
if(n == 1) {
return 0;
} else {
return 1 + halvings(n / 2); // (this uses integer division)
}
}
Problem Q3rB.7.
Without using loops (i.e., by using recursion), write a method
repeat that takes two parameters — a word and an
integer — and returns a String containing that word repeated
as often as specified in the parameter. For example, a call to
repeat("tar", 2) should return
tartar.
public String repeat(String word, int number) {
if(number == 0) return "";
else return word + repeat(number - 1);
}