This book is now obsolete Please use CSAwesome instead.

12.1. Recursion

The following video is also on YouTube at https://youtu.be/V2S_8E_ubBY. It introduces the concept of recursion.

The AP CS A exam usually has about 4-6 recursion problems. You only need to know how to trace recursive methods (figure out what they return or print). You will not be asked to write a recursive method on the exam.

12.2. What is Recursion?

Recursion is when a method calls itself. See the example method below.

1
2
3
4
5
public static void neverEnd()
{
  System.out.println("This is the method that never ends!");
  neverEnd();
}

This method will print out “This is the method that never ends!” and then call itself, which will print out the message again, and then call itself, and so on. This is called infinite recursion, which is a recursion that never ends. Of course, this particular method is not very useful.

See the method factorial below that calculates the factorial of a number. The factorial of a number is defined as 1 for 0 and n * factorial (n-1) for any other number.

1
2
3
4
5
6
7
public static int factorial(int n)
{
    if (n == 0)
        return 1;
    else
        return n * factorial(n-1);
}

Run the code below to test the factorial method.

The factorial method has a way to stop the recursion (not call itself). It stops when n is equal to 0, since it just returns 1.

Note

The thing that stops a recursive method from calling itself is called the base case. A method can have more than one base case (way to stop the recursion).

Check your understanding

You have attempted of activities on this page