Task 1 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 — base case and recursive case

Lesson

A method that calls itself

A recursive method is a method that calls itself to solve a smaller version of the same problem. Every recursive method needs two parts: a base case — a condition that stops the recursion and returns without calling again — and a recursive case — the call to itself, always with an argument that moves closer to the base case.


Worked example

static void countdown(int n) {
    if (n == 0) {          // base case: stop here
        System.out.println("Done");
        return;
    }
    System.out.println(n); // recursive case
    countdown(n - 1);      // call itself, closer to 0
}

countdown(3);   // prints 3, then 2, then 1, then Done

Each call prints n and then calls countdown(n - 1). When n reaches 0 the base case prints Done and stops — without a base case it would never stop.


▶ Try it: run this, then change countdown(3) to a different number and re-run. Watch how many lines print.



A recursive method is a method that...


Which part stops a recursive method from calling itself forever?


Type exactly what this program prints:

public class Main {
    static void countdown(int n) {
        if (n == 0) { System.out.println("Done"); return; }
        System.out.println(n);
        countdown(n - 1);
    }
    public static void main(String[] args) {
        countdown(2);
    }
}

Match each term to its meaning.


True or false?