CodeBlanks Logo Icon CodeBlanks

Base case

The base case stops the recursion.

Choosing the base case

The base case directly solves the smallest version of the problem. Choosing the right base case ensures recursion works correctly.

For example, in computing n! the base case is 0! = 1. In summing, the base case is returning 0 for an empty array.

Recursive step

The recursive step reduces the problem to a smaller version and calls the function with it. Each call gets closer to the base case.

For example, sum(n) = n + sum(n-1). Each call decreases n and eventually reaches the base case (n=0).

Practice Sum (recursive)

Write sum_recursive(n). If n=0 return 0, else n + sum_recursive(n-1). Print 15 with print(sum_recursive(5)).

Starter code

solution.py
def sum_recursive(n):
    # Compute sum

Sample solution

solution.py
def sum_recursive(n):
    # Compute sum
    if n == 0:
        return 0
    return n + sum_recursive(n - 1)
print(sum_recursive(5))

Expected output

15

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Base value

Question
0! is defined as ____.
Answer
0! is defined as 1.

Explanation: 1 is right.

2 Base case: match the terms

Term Meaning
Base case Stops
Recursive step Reduces
0! = 1 Base
n! = n*(n-1)! Recursive

3 What happens without a base case?

  • Ends immediately
  • Infinite calls and stack overflow Correct answer
  • Runs fast
  • Becomes a loop

Explanation: Infinite calls and stack overflow.

All lessons in Beginner