Chapter 3.5: Recursion

Object Oriented Programming with Java
Base caseCall stackFactorial and sumFibonacci, Lucas, Catalan, Bell Palindromes and GCDTowers of HanoiEfficiency and loopsTail recursionMemoization
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Concept

Define recursion, the base case and the recursive step; reduce a problem to a smaller copy of itself.

How it works

Trace step by step how frames pile up on the call stack and return; draw a call tree.

Writing

Write recursive Java methods for factorial, sum, series, digit sum, palindromes, GCD and the Towers of Hanoi.

Errors

Recognize and prevent infinite recursion, StackOverflowError and missing return statements.

Efficiency

Compare recursive and iterative solutions; convert recursion to a loop when needed.

Advanced techniques

Explain tail recursion and memoization; eliminate repeated computation.

The Concept of Recursion

What Is Recursion?

  • Recursion: a method solving a task by breaking it into smaller pieces and calling itself.
  • Each call solves a smaller instance of the same problem; the smallest instance is solved directly.
  • The process is self-similar: a structure contains a smaller structure of the same kind.
  • For some problems (trees, series, divide and conquer) it gives clearer and cleaner solutions than loops.
Java has no keyword for recursion: a method simply calls itself by name in its body.
Matryoshka dollsEach doll holds a smaller one; the smallest does not open (the base case).
Which row am I in?Everyone asks the person in front, who asks the next… The first row says "1"; on the way back each person adds 1.
Facing mirrorsAn image within an image: recursion without a base case never ends.

The Concept of Recursion

Base Case and Recursive Step

1. Base caseThe smallest problem, whose answer is known directly. The method does not call itself here, so the recursion stops. E.g. 1! = 1.
2. Recursive stepThe method makes the problem one step smaller, calls itself on it and builds its answer from the result. E.g. 4! = 4 × 3!.

It mirrors the inductive definition in mathematics:
n! = 1 (if n ≤ 1),   n! = n × (n − 1)! (if n > 1)

factorial(4) = 4 × factorial(3)factorial(3) = 3 × factorial(2)factorial(2) = 2 × factorial(1)factorial(1) = 1base case: no self-call

The Concept of Recursion

Call Stack

  • Each method call opens a stack frame in memory, holding the parameters, local variables and return address.
  • Frames are stacked on the call stack; only the top frame runs, the others wait.
  • In recursion, several frames of the same method are alive at once, each with its own n.
  • When the method executes return, its frame is removed and the value goes to the frame below (last in, first out: LIFO).
  • The stack is limited in size; very deep recursion ends with StackOverflowError.
main()waiting for factorial(4)factorial(4)n = 4 · waits on 4 * ?factorial(3)n = 3 · waits on 3 * ?factorial(2)n = 2 · waits on 2 * ?factorial(1)n = 1 · return 1call: frame pushedreturn: frame poppedtop of stack (running now)

Factorial and Sum

Computing a Factorial

int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;   // base case
    } else {
        return n * factorial(n - 1); // recursion
    }
}
Mathematicsn! = 1 × 2 × … × n
n! = n × (n − 1)!,  0! = 1! = 1
Lines 2–3: base case0! = 1! = 1; recursion stops here.
Line 5: recursive stepn! is (n − 1)! times n.
ProgressEach call decreases n by 1 → for n ≥ 0 the base case is always reached.
Overflowint cannot hold 13!: factorial(13) = 1932053504 (wrong!). long works up to 20!.

Calls: factorial(5) → 120 · factorial(0) → 1

Factorial and Sum

Expanding factorial(4)

factorial(4)
  = 4 * factorial(3)
  = 4 * (3 * factorial(2))
  = 4 * (3 * (2 * factorial(1)))
  = 4 * (3 * (2 * 1))
  = 4 * (3 * 2)
  = 4 * 6
  = 24
Descent (calls)In the first four lines each call opens another; the multiplications are deferred, because the right-hand value is not known yet.
Bottom (base case)factorial(1) returns 1 directly. Since the code stops at n == 1, factorial(0) is never called.
Ascent (returns)The pending multiplications complete from the inside out: 2 × 1, 3 × 2, 4 × 6.

Factorial and Sum · Step-by-step code trace

factorial(4): Step-by-Step Code Trace

factorial(4)factorial(3)factorial(2)factorial(1)

main calls factorial(4) and waits to print the result.

factorial(4)n = 4factorial(3)factorial(2)factorial(1)

New frame: n = 4. The condition n == 0 || n == 1 is false → not the base case.

factorial(4)4 * ?factorial(3)factorial(2)factorial(1)

4 * factorial(3) must be computed. The multiplication waits; first factorial(3) is called.

factorial(4)4 * ?factorial(3)n = 3factorial(2)factorial(1)

New frame: n = 3. The condition n == 0 || n == 1 is false → not the base case.

factorial(4)4 * ?factorial(3)3 * ?factorial(2)factorial(1)

3 * factorial(2) must be computed. The multiplication waits; first factorial(2) is called.

factorial(4)4 * ?factorial(3)3 * ?factorial(2)n = 2factorial(1)

New frame: n = 2. The condition n == 0 || n == 1 is false → not the base case.

factorial(4)4 * ?factorial(3)3 * ?factorial(2)2 * ?factorial(1)

2 * factorial(1) must be computed. The multiplication waits; first factorial(1) is called.

factorial(4)4 * ?factorial(3)3 * ?factorial(2)2 * ?factorial(1)return 1

n = 1: base case. No new call is made; 1 is returned. The frames now start to return.

factorial(4)4 * ?factorial(3)3 * ?factorial(2)2 * 1 = 2factorial(1)= 1

factorial(1) returns 1 and is popped: 2 * 1 = 2 is returned.

factorial(4)4 * ?factorial(3)3 * 2 = 6factorial(2)= 2factorial(1)= 1

factorial(2) returns 2 and is popped: 3 * 2 = 6 is returned.

factorial(4)4 * 6 = 24factorial(3)= 6factorial(2)= 2factorial(1)= 1

factorial(3) returns 6 and is popped: 4 * 6 = 24 is returned.

factorial(4)= 24factorial(3)= 6factorial(2)= 2factorial(1)= 1

24 returns to main and is printed. 4 calls were made; at the deepest point the stack held 5 frames.

static int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

public static void main(String[] args) {
    System.out.println(factorial(4));
}

Factorial and Sum

Computing a Sum

int sum(int n) {
    if (n == 1) {
        return 1;
    } else {
        return n + sum(n - 1);
    }
}

Sum of the numbers from 1 to n: sum(n) = n + sum(n − 1), sum(1) = 1.

sum(5) = 5 + sum(4)
       = 5 + (4 + (3 + (2 + sum(1))))
       = 5 + (4 + (3 + (2 + 1)))
       = 15

Same pattern as factorial; only × becomes +, and the base case differs. sum(100) = 5050.

The only base case is n == 1. sum(0) or a negative argument never makes n equal 1: 0, −1, −2, … infinite recursion → StackOverflowError.

A safe version uses the base case if (n <= 0) return 0;, which also catches every invalid input.

Series

Fibonacci Series

  • Starts with 0, then 1: F(0) = 0, F(1) = 1.
  • General formula: F(n) = F(n − 1) + F(n − 2): each term is the sum of the previous two.
  • The method calls itself twice: the calls form a tree (tree recursion).
int fibonacci(int n) {
    if (n <= 1) {
        return n;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}
n0123456789101112
F(n)01123581321345589144

Known from the rabbit-breeding problem (Leonardo Fibonacci, 1202). The ratio of consecutive terms approaches the golden ratio (≈ 1.618): 144 / 89 ≈ 1.618.

Series · Step-by-step code trace

fibonacci(4): Call Tree and Stack

fib(4)?fib(3)fib(2)fib(1)fib(0)fib(1)fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

fibonacci(4): n > 1. The left term of the sum comes first: fibonacci(3) is called.

fib(4)?fib(3)?fib(2)fib(1)fib(0)fib(1)fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

fibonacci(3): n > 1. The left term of the sum comes first: fibonacci(2) is called.

fib(4)?fib(3)?fib(2)?fib(1)fib(0)fib(1)fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

fibonacci(2): n > 1. The left term of the sum comes first: fibonacci(1) is called.

fib(4)?fib(3)?fib(2)?fib(1)= 1fib(0)fib(1)fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

fibonacci(1): n <= 1 → base case, 1 is returned.

fib(4)?fib(3)?fib(2)1 + ?fib(1)= 1fib(0)fib(1)fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

The left term gave 1. Now the right term: fibonacci(0) is called.

fib(4)?fib(3)?fib(2)1 + ?fib(1)= 1fib(0)= 0fib(1)fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

fibonacci(0): n <= 1 → base case, 0 is returned.

fib(4)?fib(3)?fib(2)= 1fib(1)= 1fib(0)= 0fib(1)fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

1 + 0 = 1 is returned.

fib(4)?fib(3)1 + ?fib(2)= 1fib(1)= 1fib(0)= 0fib(1)fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

The left term gave 1. Now the right term: fibonacci(1) is called.

fib(4)?fib(3)1 + ?fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

fibonacci(1): n <= 1 → base case, 1 is returned.

fib(4)?fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

1 + 1 = 2 is returned.

fib(4)2 + ?fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

The left term gave 2. Now the right term: fibonacci(2) is called.

fib(4)2 + ?fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)?fib(1)fib(0)running nowon the stack, waitingreturned a valuenot called yet

fibonacci(2): n > 1. The left term of the sum comes first: fibonacci(1) is called.

fib(4)2 + ?fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)?fib(1)= 1fib(0)running nowon the stack, waitingreturned a valuenot called yet

fibonacci(1): n <= 1 → base case, 1 is returned.

fib(4)2 + ?fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)1 + ?fib(1)= 1fib(0)running nowon the stack, waitingreturned a valuenot called yet

The left term gave 1. Now the right term: fibonacci(0) is called.

fib(4)2 + ?fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)1 + ?fib(1)= 1fib(0)= 0running nowon the stack, waitingreturned a valuenot called yet

fibonacci(0): n <= 1 → base case, 0 is returned.

fib(4)2 + ?fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)= 1fib(1)= 1fib(0)= 0running nowon the stack, waitingreturned a valuenot called yet

1 + 0 = 1 is returned.

fib(4)= 3fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)= 1fib(1)= 1fib(0)= 0running nowon the stack, waitingreturned a valuenot called yet

2 + 1 = 3 is returned. In total 9 calls; fibonacci(2) was computed twice.

static int fibonacci(int n) {
    if (n <= 1) {
        return n;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

Series

Lucas Series

  • Starts with 2, then 1: L(0) = 2, L(1) = 1.
  • Same general formula as Fibonacci: L(n) = L(n − 1) + L(n − 2).
  • Only the starting values differ → two separate base cases are needed.
int lucas(int n) {
    if (n == 0) {
        return 2;
    } else if (n == 1) {
        return 1;
    } else {
        return lucas(n - 1) + lucas(n - 2);
    }
}
n012345
L(n)2134711
n678910
L(n)18294776123

The two series are linked: L(n) = F(n − 1) + F(n + 1). E.g. L(5) = F(4) + F(6) = 3 + 8 = 11.

Series

Catalan Series

  • Starts with 1: C(0) = 1, C(1) = 1.
  • Closed form: C(n) = (2n)! / ((n + 1)! · n!).
  • Recursive formula used by the code: C(n) = Σ C(i) · C(n − 1 − i), i = 0 … n − 1.
  • The recursion runs inside a loop: each C(n) is built from all smaller C values.
long catalan(int n) {
    if (n <= 1) {
        return 1;
    }
    long result = 0;
    for (int i = 0; i < n; i++) {
        result += catalan(i) * catalan(n - i - 1);
    }
    return result;
}

Values:

112514421324291430

What does it count? The valid arrangements of n pairs of parentheses. n = 3 → C(3) = 5:

((()))(()())(())()()(())()()()

Also the ways to parenthesize a product of n + 1 numbers, and the binary trees with n nodes.

Series

Bell Series

  • Starts with 1: B(0) = 1, B(1) = 1.
  • General formula: B(n) = Σ C(n − 1, k) · B(k), k = 0 … n − 1; here C(n, k) is the binomial coefficient.
int bell(int n) {
    if (n == 0) { return 1; }
    int count = 0;
    for (int k = 0; k < n; k++) {
        count += choose(n - 1, k) * bell(k);
    }
    return count;
}

int choose(int n, int k) {       // C(n, k)
    return factorial(n) / (factorial(k) * factorial(n - k));
}

Values:

11251552203877

What does it count? The ways to partition a set of n elements into groups. {a, b, c} → B(3) = 5:

abca|bcb|acc|aba|b|c
choose uses factorial, which returns int; 13! overflows, so the code is correct only for n ≤ 13.

Writing Recursive Methods

Two Basic Rules

Rule 1: Base case

At least one base case is needed to avoid infinite recursion. For example, when n is 0 or 1 the method must finish without calling itself.

Rule 2: Make progress

Every recursive call must move toward the base case: the parameter shrinks (or grows), the string gets shorter, the range narrows.

factorial(4)factorial(3)factorial(2)factorial(1)each call: n − 1, progressbase case: no call
  • Infinite recursion (no base case, or it is never reached) and insufficient progress (the parameter does not change) are the two most common errors.
  • Each recursive call should work on a smaller part of the problem.
  • The base case is always tested before the recursive call.
  • Consider every possible input: do a negative number, 0 and an empty string reach the base case?

Writing Recursive Methods

Infinite Recursion

public class Sum {
    static int sum(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n + sum(n - 1);   // line 6
        }
    }
    public static void main(String[] args) {
        System.out.println(sum(0));
    }
}
Exception in thread "main" java.lang.StackOverflowError
	at Sum.sum(Sum.java:6)
	at Sum.sum(Sum.java:6)
	at Sum.sum(Sum.java:6)
	...

sum(0): n = 0, −1, −2, … never reaches 1. Each call opens a new frame; after some ten thousand calls the stack is full and the JVM stops the program.

The compiler does not catch this error; it appears at run time. In the stack trace, the same line repeating is the sign of infinite recursion.

Fix: widen the base case (n <= 1), validate the input, or switch to a loop when the depth is very large.

Writing Recursive Methods · Step-by-step code trace

sum(0): How Does the Stack Fill Up?

stack limitmainmain

main calls sum(0). The only base case is n == 1.

stack limitmainsum(0)n = 0

n = 0: 0 == 1 is false → 0 + sum(-1) must be computed: a new call.

stack limitmainsum(0)sum(-1)n = -1

n = -1: still not 1. With each call n moves away: the base case will never be reached.

stack limitmainsum(0)sum(-1)sum(-2)n = -2

Each call pushes a new frame; none can return, since each waits for the next one's result.

stack limit1001 framesn = -999

After a thousand calls the stack holds 1001 frames; still no error.

stack limit≈ 10,200 framesoverflow

The memory reserved for the stack is full: the JVM throws StackOverflowError. On this machine the measured depth is ≈ 10,200 calls; it depends on JVM settings.

public class Sum {
    static int sum(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n + sum(n - 1);   // line 6
        }
    }
    public static void main(String[] args) {
        System.out.println(sum(0));
    }
}

Writing Recursive Methods

Thinking Recursively

  1. Reduce: express the problem in terms of a smaller copy of itself.
  2. Base case: find the smallest input whose answer is known directly.
  3. Trust: the smaller copy is assumed to be solved correctly (the leap of faith); do not unfold the call in your head.
  4. Combine: build the big answer from the small one.

Example: the number of digits in a number.

  • Digits of 48729 = 1 + digits of 4872.
  • A one-digit number (n < 10) → 1.
int countDigits(int n) {
    if (n < 10) {                       // base case
        return 1;
    }
    return 1 + countDigits(n / 10);     // reduce + combine
}

countDigits(48729) → 5 · countDigits(7) → 1

Examples

Digit Sum

int digitSum(int n) {
    if (n < 0) {
        return digitSum(-n);
    } else if (n < 10) {
        return n;
    } else {
        return digitSum(n / 10) + (n % 10);
    }
}
  • A negative number is first made positive (lines 2–3).
  • A one-digit number is its own digit sum: base case (lines 4–5).
  • Otherwise: last digit + sum of the remaining digits.
  • For Integer.MIN_VALUE, -n is still negative: infinite recursion (compute with long).
n = 48729n / 10 = 4872n % 10 = 9recursionlast digit

n / 10 (integer division) drops the last digit; n % 10 yields the last digit. Each call shortens the number by one digit → progress is guaranteed.

Examples

Expanding digitSum(-48729)

digitSum(-48729)
  = digitSum(48729)
  = digitSum(4872) + 9
  = (digitSum(487) + 2) + 9
  = ((digitSum(48) + 7) + 2) + 9
  = (((digitSum(4) + 8) + 7) + 2) + 9
  = (((4 + 8) + 7) + 2) + 9
  = ((12 + 7) + 2) + 9
  = (19 + 2) + 9
  = 21 + 9
  = 30

The first call fixes the sign; after that each step leaves its last digit (9, 2, 7, 8) outside as a pending addition.

Base case digitSum(4) → 4. On the way back the additions run from the inside out: 4 + 8 + 7 + 2 + 9 = 30.

6 calls in total (1 for the sign + 5 digits).

Examples · Step-by-step code trace

digitSum(-357): Step-by-Step Code Trace

r(-357)r(357)r(35)r(3)

main calls digitSum(-357) (r for short in the figure).

r(-357)n < 0r(357)r(35)r(3)

n = -357: negative → first branch. The sign is fixed and r(357) is called; this frame will just pass the result back.

r(-357)→ r(357)r(357)r(35) + 7r(35)r(3)

n = 357: not below 10. 357 / 10 = 35 is the next argument; the last digit 7 stays as a pending addition.

r(-357)→ r(357)r(357)r(35) + 7r(35)r(3) + 5r(3)

n = 35: r(3) is called; 5 waits.

r(-357)→ r(357)r(357)r(35) + 7r(35)r(3) + 5r(3)return 3

n = 3 < 10: base case, 3 is returned. The frames now start to return.

r(-357)→ r(357)r(357)r(35) + 7r(35)3 + 5 = 8r(3)= 3

r(35) got 3: 3 + 5 = 8 is returned.

r(-357)→ r(357)r(357)8 + 7 = 15r(35)= 8r(3)= 3

r(357) got 8: 8 + 7 = 15 is returned.

r(-357)= 15r(357)= 15r(35)= 8r(3)= 3

r(-357) returns the 15 unchanged.

r(-357)= 15r(357)= 15r(35)= 8r(3)= 3

15 is printed: 3 + 5 + 7 = 15. Four calls were made (1 for the sign + 3 digits).

static int digitSum(int n) {
    if (n < 0) {
        return digitSum(-n);
    } else if (n < 10) {
        return n;
    } else {
        return digitSum(n / 10) + (n % 10);
    }
}

public static void main(String[] args) {
    System.out.println(digitSum(-357));
}

Examples

Checking a Palindrome

static boolean isPalindrome(String s) {
    if (s.length() <= 1) {
        return true;
    } else if (s.charAt(0) == s.charAt(s.length() - 1)) {
        return isPalindrome(s.substring(1, s.length() - 1));
    }
    return false;
}

isPalindrome("kayak") → true · isPalindrome("abba") → true · isPalindrome("java") → false

kayakoutside in: k = k, a = a; y remains
  • Palindrome: a string that reads the same backward (kayak, never odd or even).
  • s.charAt(i): the character at index i (from 0).
  • s.substring(1, s.length() - 1): the string without its first and last letters.
  • Two base cases: length ≤ 1 → true; ends differ → false.
  • Case-sensitive: "Kayak" → false.

Examples · Step-by-step code trace

isPalindrome("racecar"): Step-by-Step Code Trace

r0a1c2e3c4a5r6s = "racecar" (length 7)

s = "racecar": length 7 > 1. The first letter 'r' is compared with the last letter 'r' → equal.

r0a1c2e3c4a5r6s = "racecar" (length 7)

The ends match; the inner part s.substring(1, 6) = "aceca" is checked by a new call.

r0a1c2e3c4a5r6s = "aceca" (length 5)

s = "aceca": length 5 > 1. The first letter 'a' is compared with the last letter 'a' → equal.

r0a1c2e3c4a5r6s = "aceca" (length 5)

The ends match; the inner part s.substring(1, 4) = "cec" is checked by a new call.

r0a1c2e3c4a5r6s = "cec" (length 3)

s = "cec": length 3 > 1. The first letter 'c' is compared with the last letter 'c' → equal.

r0a1c2e3c4a5r6s = "cec" (length 3)

The ends match; the inner part s.substring(1, 2) = "e" is checked by a new call.

r0a1c2e3c4a5r6s = "e" (length 1)

Length 1 ≤ 1 → base case: a one-letter string is a palindrome, true is returned.

r0a1c2e3c4a5r6s = "cec" (length 3)

The isPalindrome("cec") frame gets true and returns true.

r0a1c2e3c4a5r6s = "aceca" (length 5)

The isPalindrome("aceca") frame gets true and returns true.

r0a1c2e3c4a5r6s = "racecar" (length 7)

The isPalindrome("racecar") frame gets true and returns true. Result: "racecar" is a palindrome.

static boolean isPalindrome(String s) {
    if (s.length() <= 1) {
        return true;
    } else if (s.charAt(0) == s.charAt(s.length() - 1)) {
        return isPalindrome(s.substring(1, s.length() - 1));
    }
    return false;
}

Examples

Greatest Common Divisor

static int gcd(int x, int y) {
    if (y == 0) {
        return x;
    }
    return gcd(y, x % y);
}
  • Euclid's algorithm: gcd(x, y) = gcd(y, x mod y).
  • Base case: if y = 0, then gcd = x.
  • The remainder shrinks at every step → it must reach 0.
  • gcd(93, 444): its first step is gcd(444, 93); the order does not matter.
gcd(444, 93)
  = gcd(93, 72)     // 444 % 93 = 72
  = gcd(72, 21)     // 93 % 72 = 21
  = gcd(21, 9)      // 72 % 21 = 9
  = gcd(9, 3)       // 21 % 9 = 3
  = gcd(3, 0)       // 9 % 3 = 0
  = 3

gcd: greatest common divisor. gcd(48, 18) → 6.

Examples · Step-by-step code trace

gcd(444, 93): Step-by-Step Code Trace

callxyx % y
gcd(444, 93)4449372

y = 93 ≠ 0. Remainder 444 % 93 = 72; new call gcd(93, 72).

callxyx % y
gcd(444, 93)4449372
gcd(93, 72)937221

y = 72 ≠ 0. Remainder 93 % 72 = 21; new call gcd(72, 21).

callxyx % y
gcd(444, 93)4449372
gcd(93, 72)937221
gcd(72, 21)72219

y = 21 ≠ 0. Remainder 72 % 21 = 9; new call gcd(21, 9).

callxyx % y
gcd(444, 93)4449372
gcd(93, 72)937221
gcd(72, 21)72219
gcd(21, 9)2193

y = 9 ≠ 0. Remainder 21 % 9 = 3; new call gcd(9, 3).

callxyx % y
gcd(444, 93)4449372
gcd(93, 72)937221
gcd(72, 21)72219
gcd(21, 9)2193
gcd(9, 3)930

y = 3 ≠ 0. Remainder 9 % 3 = 0; new call gcd(3, 0).

callxyx % y
gcd(444, 93)4449372
gcd(93, 72)937221
gcd(72, 21)72219
gcd(21, 9)2193
gcd(9, 3)930
gcd(3, 0)30—

y == 0 → base case: x = 3 is returned. gcd(444, 93) = 3.

callxyx % y
gcd(444, 93)4449372
gcd(93, 72)937221
gcd(72, 21)72219
gcd(21, 9)2193
gcd(9, 3)930
gcd(3, 0)30—

After return gcd(…) there is nothing left to do: the value 3 is passed back unchanged through every frame (5 returns). main receives 3 as the result.

static int gcd(int x, int y) {
    if (y == 0) {
        return x;
    }
    return gcd(y, x % y);
}

Examples

Towers of Hanoi

Three pegs (A, B, C) and n disks on A, largest at the bottom. Move them all to C:

  • Move only one disk at a time, always the top one.
  • A larger disk is never placed on a smaller one.

Recursive idea: move the top n − 1 disks to the spare peg, the largest disk to the target, then the n − 1 disks from the spare onto the target.

Number of moves 2ⁿ − 1: 3 disks → 7, 10 disks → 1023, 64 disks → about 1.8 × 10¹⁹.

public class TowersOfHanoi {
    static void solve(int n, char from,
                      char to, char via) {
        if (n == 1) {   // one disk: move it
            System.out.println(n + ": " + from + "->" + to);
        } else {
            solve(n - 1, from, via, to);
            System.out.println(n + ": " + from + "->" + to);
            solve(n - 1, via, to, from);
        }
    }
    public static void main(String[] args) {
        solve(3, 'A', 'C', 'B');
    }
}

Hard to write with loops, this problem takes only a few lines with recursion.

Examples · Step-by-step code trace

Towers of Hanoi: solve(3, 'A', 'C', 'B')

ABC321

Start: 3 disks on A. solve(3, 'A', 'C', 'B'): move three disks to C, using B as the spare.

ABC321

The deepest call solve(1, A, C, B): base case, disk 1 goes straight from A to C.

ABC321

solve(2, A, B, C): disk 1 is out of the way; disk 2 goes from A to B.

ABC321

Disk 1 goes on top of disk 2: solve(1, C, B, A). The top 2 disks are now on B.

ABC213

solve(3, …) reaches its middle line: the largest disk (3) goes from A to C.

ABC123

Now the 2 disks on B go to C: solve(2, B, C, A) → first, disk 1 goes from B to A.

ABC132

Disk 2 goes from B to C, on top of disk 3.

ABC321

Last move: disk 1 from A to C. 2³ − 1 = 7 moves; the puzzle is solved.

static void solve(int n, char from,
                  char to, char via) {
    if (n == 1) {
        System.out.println(n + ": " + from + "->" + to);
    } else {
        solve(n - 1, from, via, to);
        System.out.println(n + ": " + from + "->" + to);
        solve(n - 1, via, to, from);
    }
}

Efficiency

Efficiency

  • Recursive methods can sometimes be slow: every call has a cost (opening a frame, copying parameters).
  • As recursive calls are made, the system keeps the pending partial results on the call stack.
  • If the stack overflows, the program ends with StackOverflowError.
  • When this is a problem, the fix is an iterative solution built on loops.
  • Iterative solutions keep no partial results: one frame and a few variables suffice.
Memoryfactorial(n), recursive: n frames, O(n) memory. With a loop: O(1).
Depth limitWith the default stack, a depth of a few tens of thousands of calls gives StackOverflowError.
RepetitionTree recursion (Fibonacci) may compute the same values many times.

Efficiency

Repeated Computation

fib(5)fib(4)fib(3)fib(2)fib(1)fib(0)fib(1)fib(2)fib(1)fib(0)fib(3)fib(2)fib(1)fib(0)fib(1)

fibonacci(5): 15 calls. Red nodes are values computed again, although they are already known.

ncallsF(n)
1017755
2021,8916,765
302,692,537832,040
40331,160,281102,334,155

When n grows by 1, the number of calls grows ≈ 1.6×: exponential growth. fibonacci(40) takes half a second; fibonacci(50) takes minutes.

Efficiency

Factorial with a Loop

Recursive

int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

Iterative (loop)

int factorial(int n) {
    int product = 1;
    for (int i = 1; i <= n; i++) {
        product *= i;
    }
    return product;
}
factorial(5)factorial(4)factorial(3)factorial(2)factorial(1)recursive: 5 framesproduct: 1→1→2→6→24→120loop: one frame
Same result (factorial(5) → 120). The loop version uses one frame and constant memory; the variable product accumulates the product. n ≥ 0 is assumed: for negative n the recursive version throws StackOverflowError, the loop version returns 1; 13! overflows int.

Efficiency

Digit Sum and Palindrome with Loops

Digit sum

int digitSum(int n) {
    int sum = 0;
    int rest = Math.abs(n);
    while (rest > 0) {
        sum += rest % 10;
        rest /= 10;
    }
    return sum;
}

digitSum(-48729) → 30: same as the recursive version. A digit sum cannot be negative; the sign is simply dropped with Math.abs (for Integer.MIN_VALUE, Math.abs stays negative; long rest = Math.abs((long) n) fixes it).

Palindrome

boolean isPalindrome(String s) {
    s = s.toLowerCase();
    int len = s.length();
    for (int i = 0; i < len / 2; i++) {
        if (s.charAt(i) != s.charAt(len - 1 - i)) {
            return false;
        }
    }
    return true;
}

i moves from the start, len − 1 − i from the end. toLowerCase() makes "Kayak" return true. Prefer toLowerCase(Locale.ROOT): in the default tr locale, I → ı.

Efficiency · Step-by-step code trace

Palindrome with a Loop: Step by Step

isPalindrome("Kepek")

main calls isPalindrome("Kepek").

K0e1p2e3k4

Parameter s = "Kepek": the first letter is uppercase.

k0e1p2e3k4

toLowerCase() returns a new string: s = "kepek". K and k are now the same.

k0e1p2e3k4

len = 5; the loop runs while i < 5 / 2 = 2.

k0e1p2e3k4ilen − 1 − i

i = 0: index 0 from the start and index 5 − 1 − 0 = 4 from the end are compared.

k0e1p2e3k4ilen − 1 − i'k' == 'k'

'k' == 'k': equal, so return false is not executed.

k0e1p2e3k4ilen − 1 − i

i = 1: indices 1 and 3.

k0e1p2e3k4ilen − 1 − i'e' == 'e'

'e' == 'e': equal.

k0e1p2e3k4

i = 2: 2 < 2 is false, the loop ends. The middle 'p' matches itself; no need to check it.

k0e1p2e3k4

No mismatched pair found: true is returned.

isPalindrome("Kepek")

true is printed. Only one frame was used, and no new string was created at each step as in the recursive version.

static boolean isPalindrome(String s) {
    s = s.toLowerCase();
    int len = s.length();
    for (int i = 0; i < len / 2; i++) {
        if (s.charAt(i) != s.charAt(len - 1 - i)) {
            return false;
        }
    }
    return true;
}

public static void main(String[] args) {
    System.out.println(isPalindrome("Kepek"));
}

Efficiency

Recursion or Loop?

RecursionLoop (iterative)
StoppingBase caseLoop condition
ProgressCall with a smaller argumentUpdate a counter / variable
MemoryOne frame per call: O(depth)Usually O(1)
SpeedCall overhead; repetition in tree recursionUsually faster
ErrorNo base case → StackOverflowErrorBroken condition: infinite loop (program hangs)
ReadabilityTrees, divide and conquer, Hanoi, series: very naturalNatural for simple counting and accumulating
Any recursive solution can be written with a loop (keeping its own stack if needed), and vice versa. Choose by clarity, depth and performance.

Tail Recursion

Tail Recursion

  • The method's last operation is the recursive call itself; nothing is left to do on return.
  • The result is carried in an extra accumulator parameter.
  • This form lets the compiler apply tail call optimization (TCO): the call is treated like a loop and frames do not pile up → memory efficiency.
  • Java (the JVM) does not do this: tail-recursive Java code still uses O(n) stack. Languages such as Scheme, Scala (@tailrec), Kotlin (tailrec) do it.

Not tail-recursive

return n * factorial(n - 1);
// multiply AFTER the call returns

Tail-recursive

return factorial(n - 1, n * acc);
// multiply first; the call is last
n * factorial(n - 1)factorial(n - 1, n * acc)4 * ?(4, 1)3 * ?(3, 4)2 * ?(2, 12)1(1, 24)multiplication pending on returnno pending work

Tail Recursion

Tail-Recursive Examples

int digitSum(int num, int sum) {
    if (num == 0) {
        return sum;
    } else {
        return digitSum(num / 10,
                        sum + num % 10);
    }
}

Digit sum: the last digit is added to sum before the call. digitSum(48729, 0) → 30 (for n ≥ 0).

int factorial(int n, int acc) {
    if (n == 0) {
        return acc;
    } else {
        return factorial(n - 1, n * acc);
    }
}

Factorial: the product goes into acc before the call. factorial(5, 1) → 120.

The accumulator starts at the identity element of the operation: for addition 0, for multiplication 1. A wrapper method spares the caller from passing it: int factorial(int n) { return factorial(n, 1); }

Tail Recursion · Step-by-step code trace

factorial(4, 1): Tracing Tail Recursion

factorial(4, 1)last step: callfactorial(3, 4)factorial(2, 12)factorial(1, 24)factorial(0, 24)

The multiplication happens before the call: 4 * 1 = 4 becomes the new acc; call factorial(3, 4).

factorial(4, 1)last step: callfactorial(3, 4)last step: callfactorial(2, 12)factorial(1, 24)factorial(0, 24)

The multiplication happens before the call: 3 * 4 = 12 becomes the new acc; call factorial(2, 12).

factorial(4, 1)last step: callfactorial(3, 4)last step: callfactorial(2, 12)last step: callfactorial(1, 24)factorial(0, 24)

The multiplication happens before the call: 2 * 12 = 24 becomes the new acc; call factorial(1, 24).

factorial(4, 1)last step: callfactorial(3, 4)last step: callfactorial(2, 12)last step: callfactorial(1, 24)last step: callfactorial(0, 24)

The multiplication happens before the call: 1 * 24 = 24 becomes the new acc; call factorial(0, 24).

factorial(4, 1)last step: callfactorial(3, 4)last step: callfactorial(2, 12)last step: callfactorial(1, 24)last step: callfactorial(0, 24)return 24

n == 0: base case. The result is already in acc: 24 is returned.

factorial(4, 1)last step: callfactorial(3, 4)last step: callfactorial(2, 12)last step: callfactorial(1, 24)= 24factorial(0, 24)= 24

Nothing is computed on the way back; 24 is passed up as is.

factorial(4, 1)last step: callfactorial(3, 4)last step: callfactorial(2, 12)= 24factorial(1, 24)= 24factorial(0, 24)= 24

Nothing is computed on the way back; 24 is passed up as is.

factorial(4, 1)last step: callfactorial(3, 4)= 24factorial(2, 12)= 24factorial(1, 24)= 24factorial(0, 24)= 24

Nothing is computed on the way back; 24 is passed up as is.

factorial(4, 1)= 24factorial(3, 4)= 24factorial(2, 12)= 24factorial(1, 24)= 24factorial(0, 24)= 24

The result is 24. Java does not optimize the tail call: 5 frames still went on the stack. With TCO, one frame would be enough.

static int factorial(int n, int acc) {
    if (n == 0) {
        return acc;
    } else {
        return factorial(n - 1, n * acc);
    }
}

Memoization

Memoization

  • The results of repeated computations are stored and reused (the method carries state).
  • Results go into a cache (Map); when the same argument comes again, it is returned without recomputation.
  • For each n the work is done once: the exponential number of calls drops to linear.
  • Map<Integer, Long>: key n, value F(n).

fibonacci(90) → 2880067194370816120 (instantly).

import java.util.HashMap;
import java.util.Map;

static Map<Integer, Long> memo = new HashMap<>();

static long fibonacci(int n) {
    if (memo.containsKey(n)) {
        return memo.get(n);    // computed before
    }
    if (n == 0 || n == 1) {
        return n;
    }
    long result = fibonacci(n - 1) + fibonacci(n - 2);
    memo.put(n, result);        // store the result
    return result;
}

Memoization · Step-by-step code trace

Memoized fibonacci(4): Step by Step

fib(4)callsmemo2 → ?3 → ?4 → ?

fibonacci(4) is called. The memo is empty: 4 is not there and it is not a base case → first fibonacci(3) is called.

fib(4)fib(3)callsmemo2 → ?3 → ?4 → ?

fibonacci(3): not in the memo → fibonacci(2) is called.

fib(4)fib(3)fib(2)callsmemo2 → ?3 → ?4 → ?

fibonacci(2): not in the memo → fibonacci(1) is called.

fib(4)fib(3)fib(2)fib(1)base: 1memo2 → ?3 → ?4 → ?

n = 1: base case, 1 is returned.

fib(4)fib(3)fib(2)fib(0)base: 0memo2 → ?3 → ?4 → ?

n = 0: base case, 0 is returned.

fib(4)fib(3)fib(2)= 1memo2 → 13 → ?4 → ?

fibonacci(2) = 1 + 0 = 1. The result goes into the memo: {2=1}.

fib(4)fib(3)fib(1)base: 1memo2 → 13 → ?4 → ?

fibonacci(3)'s second call, fibonacci(1): base case, 1.

fib(4)fib(3)= 2memo2 → 13 → 24 → ?

fibonacci(3) = 1 + 1 = 2, stored in the memo.

fib(4)fib(2)from memo: 1memo2 → 13 → 24 → ?

The second fibonacci(2) call: it is in the memo, so 1 is returned without computing (without memoization fib(2) would make 2 more calls here: fib(1) and fib(0)).

fib(4)= 3memo2 → 13 → 24 → 3

fibonacci(4) = 2 + 1 = 3, stored in the memo. 7 calls in total (without memoization: 9).

static Map<Integer, Long> memo = new HashMap<>();
static long fibonacci(int n) {
    if (memo.containsKey(n)) {
        return memo.get(n);
    }
    if (n == 0 || n == 1) {
        return n;
    }
    long result = fibonacci(n - 1) + fibonacci(n - 2);
    memo.put(n, result);
    return result;
}

Memoization

Memoized Fibonacci: Call Tree

fib(5)= 5fib(4)= 3fib(3)= 2fib(2)= 1fib(1)= 1fib(0)= 0fib(1)= 1fib(2)= 1fib(3)= 2computedread from memo

Memoized fibonacci(5): the left branch is computed once; on the right, fib(2) and fib(3) come from the memo. 9 calls instead of 15.

ncalls without memocalls with memotime without memo (measured)time with memo
2021,89139≈ 0.5 ms< 0.1 ms
40331,160,28179≈ 0.5 s< 1 ms

With memoization the number of calls is 2n − 1. Times vary by machine; the ratio does not.

Memoization

Memoized Factorial

static Map<Integer, Long> memo = new HashMap<>();

static long factorial(int n) {
    if (memo.containsKey(n)) {
        return memo.get(n);
    }
    if (n == 0 || n == 1) {
        return 1;
    }
    long result = n * factorial(n - 1);
    memo.put(n, result);
    return result;
}
  • Same pattern: check the memo; if absent, compute, store, return.
  • long is exact up to 20!: factorial(20) = 2432902008176640000.
  • A single factorial(n) call has no repetition; the memo does not speed it up.
  • The gain appears when the program asks for factorials many times: after factorial(10), factorial(12) needs only 2 new multiplications.
  • The cost is memory: memoization trades memory for speed.

Summary

Summary

ConceptMeaning
RecursionA method calling itself on a smaller input
Base caseThe smallest case, solved directly; stops the recursion
ProgressEach call moves toward the base case (n − 1, n / 10, substring, x % y)
Call stackOne frame per call, popped in LIFO order. Too deep → StackOverflowError
Tree recursionSeveral calls (Fibonacci, Hanoi); the call count can grow exponentially
Iterative solutionLoop + accumulator variable; constant memory, usually faster
Tail recursionThe last step is the call; the result is in the accumulator. Java has no TCO
MemoizationStoring computed results in a Map and reusing them

Summary

Common Mistakes

Missing / unreachable base case

sum(0), for example: Exception in thread "main" java.lang.StackOverflowError.

No progress

return n * factorial(n); does not shrink the parameter; again StackOverflowError.

Missing return

if … else if as the last branch of a method: error: missing return statement. Fix: make the last branch else.

Ignoring the call's result

factorial(n - 1); on its own line loses the value; it should be return n * factorial(n - 1);.

Overflow

int factorial goes wrong at 13!, the Bell coefficient after 13, with no error message. Fix: long.

Needless tree recursion

Without memoization, fibonacci(50) takes minutes. Fix: a loop or memoization.

Summary

Worked Problems (1)

static void write(int n) {
    if (n == 0) return;
    System.out.print(n + " ");
    write(n - 1);
}
static void write2(int n) {
    if (n == 0) return;
    write2(n - 1);
    System.out.print(n + " ");
}
static int mystery(int a, int b) {
    if (b == 0) return 0;
    return a + mystery(a, b - 1);
}
  1. write(3): what does it print?
  2. write2(3): what does it print? Where does the difference come from?
  3. mystery(4, 3): what is its value? What does the method compute?
  4. mystery(4, -1): what happens?
Show answers
  1. 3 2 1: printing happens before the call (on the way down).
  2. 1 2 3: printing happens after the call, on the way back; the deepest frame prints first.
  3. 4 + 4 + 4 + 0 = 12: a × b computed by repeated addition.
  4. b = −1, −2, … never reaches 0 → StackOverflowError.

Summary

Worked Problems (2)

static String reverse(String s) {
    if (s.isEmpty()) return "";
    return reverse(s.substring(1)) + s.charAt(0);
}
  1. reverse("java"): what does it return?
  2. reverse: is it tail-recursive? What about gcd?
  3. fibonacci(5): how many times is it called (including the first call)?
  4. gcd(48, 18): write out the calls.
Show answers
  1. "avaj": the first letter goes after the reverse of the rest: reverse("ava") + 'j'.
  2. reverse is not: the concatenation (+) happens after the call returns. gcd is: the call is its last step.
  3. 15 calls (the number of nodes in the call tree).
  4. gcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) → 6.

Summary

Exercises

  1. long power(int base, int exp): compute base to the power exp recursively. power(2, 10) = ?
  2. void binary(int n): print the binary representation of n. binary(13) → ?
  3. int arraySum(int[] a, int i): the sum of the array from index i to the end. {3, 1, 4, 1, 5} → ?
  4. Write Fibonacci with a loop and with tail recursion (fibT(n, a, b)).
  5. lucas(5): how many calls does it make? How many with memoization?
  6. How many moves do the Towers of Hanoi need for 4 disks? What is the first move?
Answers / hints
  1. if (exp == 0) return 1; return base * power(base, exp - 1); → 1024.
  2. if (n > 1) binary(n / 2); System.out.print(n % 2); → 1101 (printing on the way back: high digits first).
  3. if (i == a.length) return 0; return a[i] + arraySum(a, i + 1); → 14.
  4. Loop: a = 0, b = 1; repeat n times (a, b) ← (b, a + b). Tail: n == 0 ? a : fibT(n - 1, b, a + b) → fibT(10, 0, 1) = 55.
  5. 15 calls (same tree shape as Fibonacci); with memoization 9 (2n − 1).
  6. 2⁴ − 1 = 15 moves. Since n is even, the first move takes disk 1 to the spare peg (A → B).

Summary

References

  • Oracle, The Java Tutorials: Defining Methods; Returning a Value from a Method.
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition (15.12 Method Invocation Expressions).
  • P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 18: Recursion).
  • A. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly (Chapter 8: Recursive Methods).
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson.
  • R. Sedgewick and K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley (2.3 Recursion).

The End

Chapter 3.5: Recursion
Previous: Chapter 3.4: Strings · Next: Chapter 4.1: Objects and Classes
1 / 1 Sercan KÜLCÜ. All rights reserved.