Back to Recursion

Lesson PreviewLesson 1 of 2 in this unit

10.1 Recursion

Part of Recursion in AP® Computer Science A. Read the opening section, then create a free account for the full interactive lesson, practice, and progress tracking.

Recursion

Every recursive method needs a base case that stops further calls and at least one recursive call that reduces the problem. The base case handles the simplest input without recursion; it prevents infinite loops. The recursive call applies the same method to a smaller or simpler input. The following example computes the factorial, which is the product of all positive integers up to a given number:

java
public int factorial(int n) {
    if (n <= 1) {             // Base case: stops recursion
        return 1;
    }
    return n * factorial(n - 1); // Recursive call: reduces the problem
}

In this unit

2 lessons

  1. 10.1RecursionThis lesson
  2. 10.2Recursive Searching and SortingPreview lesson

Continue the full lesson in Stellar

Create a free account to unlock the remaining sections, checkpoints, course practice, and progress tracking for AP® Computer Science A.