Task 7 of 10 · 0 solved · 10 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.5 Recursion — debugging and infinite recursion

Lesson

When recursion goes wrong

If a recursive method never reaches its base case, it calls itself forever. Java can't keep adding calls indefinitely, so it stops the program with a StackOverflowError. The two most common causes are: the base case condition is never true, or the recursive call moves away from the base case instead of toward it.


A broken example

static void countUp(int n) {
    if (n == 0) return;   // base case never reached from a positive n going up
    System.out.println(n);
    countUp(n + 1);       // BUG: moves away from 0, not toward it
}

countUp(3) prints 3, 4, 5, 6, ... forever and then crashes with a StackOverflowError. Changing n + 1 to n - 1 fixes it. (Because it never stops, this one is shown only as text — the runnable example below is a correct method.)


▶ Try it: this sumTo is a correct recursion. A loop from 1 to n would give the same total — recursion and iteration can solve the same problem.



What happens if a recursive method never reaches its base case?


A countdown method has these three lines in its body. It is supposed to stop at 0, but it runs forever. Click the line causing the bug.


How do you fix a recursive method whose base case is never reached?


A recursive sum of 1..n and an iterative (loop) sum of 1..n...


True or false?


Type exactly what this program prints.

public class Main {
    static int sumTo(int n) {
        if (n == 0) {
            return 0;
        }
        return n + sumTo(n - 1);
    }

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