Courses / Computer Science I
Programming II

Recursion and Iterative Alternatives

Computer Science I 268 words Free to read

Anatomy of Recursion

Recursion is when a function solves a problem by calling itself on a smaller version of the same problem.

Every correct recursive function contains two essential parts:

PartRoleExample (n!n!)
Base CaseStops recursion by answering a tiny input directly0!=10! = 1
Recursive CaseBreaks the problem down toward the base casen!=n×(n1)!n! = n \times (n-1)!

Here is the classic code implementation:

def factorial(n):
    if n == 0:        # base case
        return 1
    return n * factorial(n - 1)   # recursive case

Common pitfall: Forgetting the base case, or writing a recursive step that fails to shrink the input. Both cause infinite recursion until the call stack overflows in a stack overflow.

The Call Stack and Iteration

Each recursive call waits for the smaller call to finish, stacking up frames: factorial(3) waits for factorial(2), and so on, until 0!=10! = 1 resolves and results multiply back up.

Anything recursive can also be written iteratively with a loop, and vice versa. Use the comparison below to choose:

ApproachStrengthsWeaknesses
RecursionExpresses trees and divide-and-conquer clearlyFunction call overhead, memory cost on stack
IterationMore memory-efficient for simple repetitionCan obscure naturally recursive data structures

The choice between them is about clarity and cost, not capability. Every recursive function must have a reachable base case, and each step must make the problem strictly smaller.

Recursion and Iterative Alternatives

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes

Programming II