Chapter 12: Recursion
Multiple Choice · Basics
Question 1: Which One Never Terminates?
With which of the following bodies does the call f(5) never terminate?
B: In B, n goes 5, 3, 1, −1, −3, …; no odd number equals 0, so the base case is skipped → StackOverflowError. Writing the base case as n <= 0 prevents this.
Multiple Choice · Factorial
Question 2: Recursive Equivalent of the while Version
The factorial method with while is shown beside. Which of the following recursive f(int n) bodies gives the same result for n ≥ 0?
static long factorialLoop(int n) { long result = 1; int i = 1; while (i <= n) { result *= i; i++; } return result; }
D: 0! = 1! = 1 is the base case, and n decreases by 1 on each call. A has no base case (StackOverflowError), in B n does not shrink (StackOverflowError for n ≥ 2). C returns 0 in the base case, so every result becomes 0.
Step-by-Step Trace · Factorial
Question 3: factorial(5) Call Stack
How are calls opened and closed on the stack in recursive factorial? Trace the call stack.
main calls factorial(5) and waits for the result.
5 <= 1 → false. 5 * factorial(4): the multiplication needs the sub-result first → this frame waits.
A new frame with its own n (4). It waits for 4 * factorial(3).
Waits for 3 * factorial(2).
Waits for 2 * factorial(1).
1 <= 1 → true: base case, return 1. The stack is at its deepest: 6 frames.
The last one opened closes first: 2 * 1 = 2 is returned.
3 * 2 = 6.
4 * 6 = 24.
5 * 24 = 120.
All the multiplications were done on the way back.
static long factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } // inside main: System.out.println(factorial(5));
Output Question · Factorial
Question 4: Order of Calls and Returns
The method prints both when called and on return. What is the output?
static int f(int n) { System.out.print("g" + n + " "); if (n <= 1) return 1; int r = n * f(n - 1); System.out.print("d" + n + " "); return r; } // inside main: System.out.println(f(3));
Show answer
Output: g3 g2 g1 d2 d3 6
- While calls are being opened, the "g" lines are printed in order: 3, 2, 1.
- Since f(1) executes
returnin the base case, "d1" is not printed. - Frames close in reverse order: d2, d3. Finally main prints the result (3·2·1 = 6).
Multiple Choice · Exponentiation
Question 5: Without a Negative Exponent Check
In the recursive power method from the lecture, what happens if power(2, -1) is called?
static long power(long base, int n) { if (n == 0) return 1; return base * power(base, n - 1); }
C: n goes −1, −2, −3, …; the base case n == 0 is never reached and frames pile up. Remedy: throw an error for n < 0, or make the return type double and convert to a positive exponent with 1.0 / power(base, -n).
Output Question · Exponentiation
Question 6: Fully Recursive Power
This idea has been moved into a fully recursive method. What is the output?
static double power(double t, int n) { if (n < 0) return 1.0 / power(t, -n); if (n == 0) return 1; return t * power(t, n - 1); } // inside main: System.out.println(power(2, -2) + " " + power(3, 3));
Show answer
Output: 0.25 27.0
- power(2, −2) → 1.0 / power(2, 2); power(2, 2) = 2 · 2 · 1 = 4.0 → 0.25.
- power(3, 3) = 3 · 3 · 3 · 1 = 27.0 (n + 1 = 4 calls).
- The negative branch runs only in the first call; in later calls n ≥ 0.
Multiple Choice · Exponentiation
Question 7: Number of Calls in Fast Power
How many calls in total does fastPower(3, 16) from the lecture make (including the first call)?
static long fastPower(long base, int exp) { if (exp == 0) return 1; long half = fastPower(base, exp / 2); if (exp % 2 == 0) return half * half; return half * half * base; }
D: The exponent is halved on each call: 16 → 8 → 4 → 2 → 1 → 0, i.e. 6 calls (log₂16 + 2). The plain power method would make 17 calls. The result is 3¹⁶ = 43,046,721.
Step-by-Step Trace · Digits
Question 8: rakamSumi(908)
Trace the method that finds the sum of digits recursively using the call stack. What is the output?
main calls rakamSumi(908).
908 < 10 → false. The last digit 908 % 10 = 8 is held; a new call with 908 / 10 = 90.
90 < 10 → false. 90 % 10 = 0 is held; a call with 9.
9 < 10 → true: a single digit, return 9 (base case).
0 + 9 = 9 is returned.
8 + 9 = 17 is returned.
9 + 0 + 8 = 17. Depth = number of digits (3).
static int rakamSumi(int n) { if (n < 10) return n; return n % 10 + rakamSumi(n / 10); } // inside main: System.out.println(rakamSumi(908));
Output Question · Digits
Question 9: Recursive Digit Count
The digit count method written with a loop is rewritten recursively. What is the output?
static int digitCount(int n) { n = Math.abs(n); if (n < 10) return 1; return 1 + digitCount(n / 10); } // inside main: System.out.println(digitCount(123456)); System.out.println(digitCount(0) + " " + digitCount(-470));
Show answer
Output:
6 1 3
- Each call drops the last digit (n / 10) and adds 1; when it reaches a single digit it returns 1.
- 0 is a single digit → 1 (the base case
n < 10covers this naturally). - For a negative number,
Math.abscomes first: −470 → 470 → 3.
Output Question · Digits
Question 10: Print Before or After the Call?
The two methods differ only in the order of printing and the recursive call. What is the output?
static void printA(int n) { if (n == 0) return; System.out.print(n % 10); printA(n / 10); } static void printB(int n) { if (n == 0) return; printB(n / 10); System.out.print(n % 10); } // inside main: printA(472); System.out.print(" "); printB(472);
Show answer
Output: 274 472
- printA prints first, then calls: the last digits are printed while the calls are being opened → 2, 7, 4 (reverse order).
- printB calls first and leaves printing for the return: the deepest call (n = 4) prints first → 4, 7, 2 (original order).
Step-by-Step Trace · Sum
Question 11: Recursive Sum of an Array
The sum of the array is found with the definition sum(a, i) = a[i] + sum(a, i + 1). Trace the call stack.
The array is created; all calls share the same array (reference).
0 == 3 → false. a[0] = 4 is held and sum(a, 1) is called.
a[1] = 7 is held, sum(a, 2).
a[2] = 2 is held, sum(a, 3).
3 == a.length → base case: return 0 (the end of the array).
2 + 0 = 2 is returned.
7 + 2 = 9 is returned.
4 + 9 = 13 is returned.
An array of n elements makes n + 1 calls; the stack depth is O(n).
static int sum(int[] a, int i) { if (i == a.length) return 0; return a[i] + sum(a, i + 1); } // inside main: int[] d = {4, 7, 2}; System.out.println(sum(d, 0));
Classic Question · Fibonacci
Question 12: fib(4) Recursion Tree
Draw the recursion tree of fib(4) for the plain recursive fib method (if (n <= 1) return n; return fib(n - 1) + fib(n - 2);). How many calls are made in total; how many times are fib(2), fib(1) and fib(0) called?
Show answer
9 calls: fib(4) 1, fib(3) 1, fib(2) 2, fib(1) 3, fib(0) 2 times. Result fib(4) = 3.
The subtrees of fib(n − 1) and fib(n − 2) overlap; the number of calls grows roughly exponentially with n (fib(5): 15, fib(30): 2,692,537 calls).
Step-by-Step Trace · Fibonacci
Question 13: fib(3) Step by Step
Follow the stack during the call fib(3) and which call in the tree is running. What is the output?
main calls fib(3).
3 <= 1 → false. The left term fib(2) will be computed first.
2 <= 1 → false. fib(1) first.
Base case: return 1.
The left term 1 is ready; now the right term fib(0).
Base case: return 0.
fib(2) = 1 + 0 = 1 is returned; its frame closed.
fib(3) now calls the right term fib(1) → base case, 1.
fib(3) = 1 + 1 = 2.
5 calls were made; the stack grew to at most 4 frames (including main).
static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } // inside main: System.out.println(fib(3));
Multiple Choice · Fibonacci
Question 14: Number of Calls for fib(5)
How many times in total is the method called while computing fib(5) with the plain recursive fib (including the first call)?
D: The number of calls is calls(n) = 1 + calls(n − 1) + calls(n − 2), calls(0) = calls(1) = 1: calls(2) = 3, calls(3) = 5, calls(4) = 9, calls(5) = 15. Even though the result is fib(5) = 5, 15 calls are made.
Multiple Choice · Optimization
Question 15: Number of Calls with Memoization
How many calls in total does the memoized fib(6) make (memo initially empty)? (The plain version makes 25 calls.)
static long[] memo = new long[50]; static long fib(int n) { if (n <= 1) return n; if (memo[n] != 0) return memo[n]; memo[n] = fib(n - 1) + fib(n - 2); return memo[n]; }
B: Each fib(k) (k ≥ 2) is computed once and makes two calls; the right call fib(k − 2) finds the value ready in memory and returns immediately. Count: 1 + 2 × 5 = 11. The result is fib(6) = 8; in exchange O(n) memory is used.
Multiple Choice · Call Stack
Question 16: The Deepest Moment
When factorial(4) is called, how many frames does the call stack contain at its deepest moment, including main?
A: main, f(4), f(3), f(2), f(1): when the base case is reached no call has returned yet, all are on the stack. The loop version uses only 2 frames (main + method).
Multiple Choice · Optimization
Question 17: Tail Recursion Chain
Which is the chain of the call factTail(4, 1)?
static long factTail(int n, long acc) { if (n <= 1) return acc; return factTail(n - 1, n * acc); }
C: The multiplication is done before the call: 4·1 = 4, 3·4 = 12, 2·12 = 24. In the base case the accumulator is returned as it is; no work is left on the way back.
Output Question · More Examples
Question 18: Decimal to Binary
What is the output of the following code?
static String toBinary(int n) { if (n < 2) return "" + n; return toBinary(n / 2) + (n % 2); } // inside main: System.out.println(toBinary(13) + " " + toBinary(6) + " " + toBinary(1));
Show answer
Output: 1101 110 1
- The remainder (n % 2) is appended to the right of the recursive call; so the last remainder found (the most significant bit) ends up leftmost.
- 13 → 6 remainder 1 → 3 remainder 0 → 1 remainder 1 → base case "1": "1" + 1 + 0 + 1.
Output Question · More Examples
Question 19: Hanoi: 2 Disks
The Hanoi method from the lecture is run with two disks. What is the output?
static void hanoi(int n, char source, char target, char spare) { if (n == 0) return; hanoi(n - 1, source, spare, target); System.out.println(n + ": " + source + " -> " + target); hanoi(n - 1, spare, target, source); } // inside main: hanoi(2, 'A', 'C', 'B');
Show answer
1: A -> B 2: A -> C 1: B -> C
- First the top disk goes to the spare peg (A → B), then the large disk to the target (A → C), finally the small disk to the target (B → C).
- The printing is between the two recursive calls (in-order traversal of the tree).
Multiple Choice · More Examples
Question 20: Number of Hanoi Moves
What is the minimum number of moves needed for 5 disks in the Towers of Hanoi?
C: h(n) = 2·h(n − 1) + 1, h(0) = 0 → 1, 3, 7, 15, 31. In general 2ⁿ − 1: 2⁵ − 1 = 31. The number of moves grows exponentially.