Tracing the factorial function

COSC 2306 - Recursive Function Call Stack Visualizer

Call Stack

Stack is currently empty.
Enter a number and click "Step" to begin tracing.

Controls

Keep small (0-6) for visualization.

# Factorial recursion visualizer ready.

Understanding Recursion

A recursive function is a function that calls itself to solve a smaller instance of the same problem. It consists of two main parts:

  • Base Case: The condition under which the function stops calling itself (e.g., n == 0 returning 1). This prevents infinite loops.
  • Recursive Step: The part where the function calls itself with a modified parameter, inching closer to the base case (e.g., n * fact(n - 1)).

Notice how the function "winds" up the stack calling itself until the base case is hit, then "unwinds" returning and multiplying the results back down!

Python Implementation
def fact(n):
    if (n == 0):
        return 1
    else:
        return n * fact(n - 1)