B2.4.4–5 · HL recursion

Recursive sum

Python · step by step

Recursive sum

Watch calls build up, reach the base case, then return in reverse order.

Select Play or Next line to follow Python execution.

Python implementation

The highlight marks the next line to execute. Values show the state before that line.

def recursive_sum(n):    if n == 0:        return 0    subtotal = recursive_sum(n - 1)    return n + subtotal

B2.4.5: a simple non-branching recursive function. Each call makes at most one recursive call. For non-negative n: O(n) time and O(n) auxiliary call-stack space. A loop can use O(1) auxiliary space.

Keep exploring

Return to the recursion lesson →

All B2.4 animations →

All practice & resources →