Recursive Methods, Tracing and the Tower of Hanoi (ISC Class 12 Computer Science)
Updated 17 October 2026 · Draft, not yet fact-checked
A recursive method calls itself on a smaller version of the problem. It must have a base case that stops the calls and a recursive case that moves towards it. Each call waits on the call stack until the smaller call returns, so trace by expanding the calls down to the base case and then substituting the results back. Tower of Hanoi with n discs needs 2^n - 1 moves.
Calls go down until the base case answers 1, then each waiting call multiplies and returns its value back up: 1, 2, 6, 24.
Illustration drawn for QuestionBuddy.
Understand Recursive Methods, Tracing and the Tower of Hanoi
Idea. Many problems have a solution built from the solution of a smaller copy of the same problem. A recursive definition is written the same way: factorial is n! = n x (n - 1)! with 0! = 1 (or 1! = 1).
Two parts. (1) Base case: the simplest input, answered directly with no further call. (2) Recursive case: calls the same method with an argument that is closer to the base case (n - 1, n / 10, a narrower range). Without a base case the calls never stop and Java throws StackOverflowError.
Typical recursive methods.
static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); }
static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); }
static int digitSum(int n) { if (n == 0) return 0; return n % 10 + digitSum(n / 10); }
static String bin(int n) { if (n == 0) return ""; return bin(n / 2) + (n % 2); }Binary search is also recursive: search the half that can hold the key, and stop when lo > hi.
Tracing. Write each call on its own line, indenting as it goes deeper, until the base case returns. Then work back up, substituting each returned value. For example fact(4) = 4 x fact(3) = 4 x 3 x fact(2) = 4 x 3 x 2 x fact(1) = 4 x 3 x 2 x 1 = 24. If a statement comes before the recursive call it runs on the way down; if it comes after the call it runs on the way back up (so the order of printing is reversed).
The call stack. Every call pushes a frame holding its own parameters and local variables; the frames are removed in last-in first-out order. Recursion therefore uses extra memory compared to a loop, and a very deep recursion can overflow the stack.
Tower of Hanoi. Move n discs from peg A to peg C using peg B, moving one disc at a time and never placing a larger disc on a smaller one. Recursive idea: move n - 1 discs from A to B, move disc n from A to C, then move the n - 1 discs from B to C. The number of moves T(n) = 2T(n - 1) + 1 gives T(n) = 2^n - 1.
Loops and iterative binary search are in other topics; time and space complexity of recursion are in the complexity chapter.
Recursive Methods, Tracing and the Tower of Hanoi: key facts
- Parts of a recursive method
- Base case stops the calls
- Recursive case calls with a smaller argument
- No base case gives StackOverflowError
- Check that every call moves towards the base case.
- Standard recursive definitions
- fact(n) = n x fact(n - 1), fact(1) = 1
- gcd(a, b) = gcd(b, a % b), gcd(a, 0) = a
- digitSum(n) = n % 10 + digitSum(n / 10), digitSum(0) = 0
- Each definition converts directly to code.
- Tower of Hanoi
- Moves for n discs = 2^n - 1
- 3 discs need 7 moves
- 4 discs need 15
- T(n) = 2T(n - 1) + 1
- T(1) = 1.
- Tracing order
- Statements before the call run going down
- Statements after the call run coming back
- Frames are removed last in, first out
- The call stack is LIFO.
How to answer Recursive Methods, Tracing and the Tower of Hanoi questions
Use this routine to dry-run a recursive method.
- 1Identify the base case and what it returns.
- 2Write the first call with its arguments, then each recursive call on a new indented line until the base case.
- 3Note any print statement and whether it is before or after the recursive call.
- 4Work back up: substitute each returned value into the waiting expression.
- 5Write the final value or the printed sequence exactly.
- 6State what the method computes in one line (for example, a x b by repeated addition).
Recursive Methods, Tracing and the Tower of Hanoi in real life
The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Adding the digits of a ticket number
Suppose a clerk adds up the digits of a ticket number by repeatedly removing the last digit, which is how digitSum recursion works.
For the ticket number 4729, what does digitSum return?
Try it first, then show the solutionSolution
- digitSum(4729) = 9 + digitSum(472).
- digitSum(472) = 2 + digitSum(47), digitSum(47) = 7 + digitSum(4), digitSum(4) = 4 + digitSum(0) = 4.
- Back up: 4, 11, 13, 22.
Answer: 22
Memory hook: Peel one digit, hand the rest to the next call.
Moving a stack of plates
Suppose three plates must be moved from tray A to tray C using tray B, one plate at a time, never putting a bigger plate on a smaller one.
How many single moves are needed?
Try it first, then show the solutionSolution
- The number of moves for n plates is 2 to the power n minus 1.
- For 3 plates: 8 - 1 = 7.
Answer: 7 moves
Memory hook: Move n - 1 away, move the big one, move n - 1 back.
Tricks to remember Recursive Methods, Tracing and the Tower of Hanoi
Short memory aids. Say each one aloud once, then use it on a question the same day.
Base case first
Write the stopping line before the recursive line.
Use it when: Writing any recursive method.
Down then up
Expand the calls going down, then collect the answers coming up.
Use it when: Dry runs.
Before or after
Print before the call: down order. Print after the call: reverse order.
Use it when: Output-order questions.
Hanoi = 2 to the n, minus 1
Double the previous count and add one: 1, 3, 7, 15, 31.
Use it when: Counting Hanoi moves.
Recursive Methods, Tracing and the Tower of Hanoi: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: Base case · 1 mark · MCQBoard level
In the recursive definition gcd(a, b) = gcd(b, a % b), which condition is the base case?
(a) a == 0 (b) b == 0 (c) a == b (d) a < b
Try it first, then show the solutionSolution
- The calls stop when the second argument becomes 0, because the answer is then the first argument.
Answer: (b) b == 0
Example 2: GCD trace · 3 marks · Short answerHarder board level
For static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } trace gcd(48, 18), counting the calls.
Try it first, then show the solutionSolution
- gcd(48, 18) calls gcd(18, 12) because 48 % 18 = 12. (1 mark)
- gcd(18, 12) calls gcd(12, 6); gcd(12, 6) calls gcd(6, 0). (1 mark)
- gcd(6, 0) has b = 0 and returns 6, which every earlier call returns. Four calls in all. (1 mark)
Answer: gcd(48, 18) = 6 with 4 calls
Example 3: Decimal to binary by recursion · 4 marks · Short answerHarder board level
For static String bin(int n) { if (n == 0) return ""; return bin(n / 2) + (n % 2); } find bin(13) and explain the order of the digits.
Try it first, then show the solutionSolution
- bin(13) = bin(6) + 1, bin(6) = bin(3) + 0, bin(3) = bin(1) + 1, bin(1) = bin(0) + 1, bin(0) = "". (1.5 marks)
- Back up: bin(1) = "1", bin(3) = "11", bin(6) = "110", bin(13) = "1101". (1.5 marks)
- The remainder is added after the recursive call, so the last remainder found (the most significant bit) appears first. (1 mark)
Answer: 1101
Example 4: Two recursive calls · 4 marks · Short answerHarder board level
Write the output of p(3):
static void p(int n) {
if (n == 0) return;
p(n - 1);
System.out.print(n % 2);
p(n - 1);
}Try it first, then show the solutionSolution
- p(1) = p(0), print 1 % 2 = 1, p(0), so it prints 1. (1 mark)
- p(2) = p(1), print 2 % 2 = 0, p(1), so it prints 1 0 1. (1.5 marks)
- p(3) = p(2), print 3 % 2 = 1, p(2), so it prints 101, then 1, then 101. (1 mark)
- Output: 1011101. (0.5 mark)
Answer: 1011101
Example 5: Case: Tower of Hanoi · 4 marks · Case-basedHOTS / competency
Suppose a game uses:
static void hanoi(int n, char from, char to, char via) {
if (n == 0) return;
hanoi(n - 1, from, via, to);
System.out.println("Move disc " + n + " from " + from + " to " + to);
hanoi(n - 1, via, to, from);
}(i) Write the output of hanoi(2, 'A', 'C', 'B'). (2 marks)
(ii) How many moves for 5 discs? (1 mark)
(iii) What would go wrong if the line if (n == 0) return; were removed? (1 mark)
Try it first, then show the solutionSolution
- (i) hanoi(2, A, C, B) first calls hanoi(1, A, B, C), which prints "Move disc 1 from A to B"; then prints "Move disc 2 from A to C"; then calls hanoi(1, B, C, A), which prints "Move disc 1 from B to C".
- (ii) 2^5 - 1 = 31 moves.
- (iii) The method would keep calling itself with n = 0, -1, -2, ... and end with StackOverflowError.
Answer: (i) Move disc 1 from A to B; Move disc 2 from A to C; Move disc 1 from B to C (ii) 31 (iii) infinite recursion, StackOverflowError
Where students lose marks in Recursive Methods, Tracing and the Tower of Hanoi
The slips examiners see most often, and what to write instead.
Mistake: Missing base case
The recursion never ends.
Wrong working
static int f(int n) { return n * f(n - 1); }
Right working
static int f(int n) { if (n <= 1) return 1; return n * f(n - 1); }
Do this: Write the stopping condition first.
Usually costs: 1 mark
Mistake: Not moving towards the base case
An argument that does not shrink gives infinite calls.
Wrong working
return gcd(a, b);
Right working
return gcd(b, a % b);
Do this: Check the argument changes in every call.
Usually costs: 1 mark
Mistake: Reversed output order
A print after the recursive call runs on the way back.
Wrong working
For static void show(int n){ if(n==0) return; System.out.print(n+" "); show(n-1); System.out.print(n+" "); }, assuming show(3) prints only 3 2 1 and ignoring the print after the call.
Right working
For the same method, show(3) prints 3 2 1 1 2 3: the first print runs going down (3 2 1), and the print after the call runs coming back (1 2 3).
Do this: Mark where each print sits relative to the call.
Usually costs: 1 mark
Exam tips
- Show every call on a separate line in the dry run, with its arguments.
- Always name the base case and say what it returns.
- Write the Hanoi formula 2^n - 1 and state the value for the given n.
- Say recursion uses a stack and extra memory when asked to compare with iteration.
- End a trace with the final answer and the number of calls if asked.
Practice questions on Recursive Methods, Tracing and the Tower of Hanoi
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
Infinite recursion in Java ends with
(a) NullPointerException (b) StackOverflowError (c) ArithmeticException (d) a compile-time errorHint
The call stack runs out.
Answer
(b) StackOverflowError
Q2 · 2 marks · Short answerBoard level
Write a recursive method to find the factorial of n. Name its base case and recursive case.
Hint
n! = n x (n - 1)!
Answer
static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } The base case is n <= 1, returning 1. The recursive case is n * fact(n - 1).
Q3 · 3 marks · Short answerHarder board level
Dry-run mystery(4, 3) and state what the method computes:
static int mystery(int a, int b) { if (b == 0) return 0; return a + mystery(a, b - 1); }Hint
Expand until b is 0.
Answer
mystery(4, 3) = 4 + mystery(4, 2) = 4 + 4 + mystery(4, 1) = 4 + 4 + 4 + mystery(4, 0) = 12 + 0 = 12. The method computes a x b by repeated addition.
Q4 · 4 marks · Short answerHarder board level
Write a recursive method to find the sum of the digits of an integer and trace it for 4729.
Hint
Use n % 10 and n / 10.
Answer
static int digitSum(int n) { if (n == 0) return 0; return n % 10 + digitSum(n / 10); } Trace: digitSum(4729) = 9 + digitSum(472) = 9 + 2 + digitSum(47) = 9 + 2 + 7 + digitSum(4) = 9 + 2 + 7 + 4 + digitSum(0) = 22.
Q5 · 4 marks · Case-basedHOTS / competency
Consider the recursive binary search below on a = {2, 5, 8, 12, 16, 23, 38}:
static int bs(int[] a, int key, int lo, int hi) { if (lo > hi) return -1; int mid = (lo + hi) / 2; if (a[mid] == key) return mid; if (a[mid] < key) return bs(a, key, mid + 1, hi); return bs(a, key, lo, mid - 1); }Find bs(a, 23, 0, 6) and bs(a, 6, 0, 6) with the number of calls for each, and name the base cases.
Hint
Write lo, hi and mid for each call.
Answer
bs(a, 23, 0, 6): mid = 3, a[3] = 12 < 23, so bs(4, 6); mid = 5, a[5] = 23 found: returns 5; two calls. bs(a, 6, 0, 6): mid = 3, 12 > 6, so (0, 2); mid = 1, 5 < 6, so (2, 2); mid = 2, 8 > 6, so (2, 1); lo > hi returns -1; four calls. Base cases: a[mid] == key (found) and lo > hi (absent).
Test your recall
Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.
1.What is a base case?Show answer
The simplest input, answered directly without a further recursive call.
2.What error does infinite recursion cause?Show answer
StackOverflowError.
3.How many moves for n discs in the Tower of Hanoi?Show answer
2^n - 1.
4.Which data structure holds the recursive calls?Show answer
The call stack (LIFO).
5.What does gcd(a, 0) return?Show answer
a.
6.When does a statement placed after the recursive call execute?Show answer
On the way back, after the smaller call returns.
Recursive Methods, Tracing and the Tower of Hanoi: frequently asked questions
What is recursion in Java?
It is a technique in which a method calls itself to solve a smaller instance of the same problem until a base case is reached.
Why is a base case necessary in recursion?
It stops the chain of calls; without it the method calls itself endlessly and the stack overflows.
How many moves are needed in the Tower of Hanoi?
For n discs the minimum number of moves is 2^n - 1.
Is recursion better than iteration?
Not always. Recursion gives short, natural solutions for problems like Hanoi, but each call uses stack memory, so a loop is more economical for simple repetition.