CS205

Factorial & Sum

Explore how recursion works with simple examples. Watch the call stack grow and unwind as the function calls itself.

Understanding Factorial

The factorial of n (written as n!) is the product of all positive integers from 1 to n:

5! = 5 × 4 × 3 × 2 × 1 = 120

Base Case

When n ≤ 1, return 1 (0! = 1! = 1)

Recursive Case

n! = n × (n-1)!

Try entering different values of n below and watch how the call stack builds up until it reaches the base case, then unwinds with the calculated values.

Factorial - Call Stack Visualizer
(max: 12)
Factorial Code
int factorial(int n) {
    // Base case: factorial of 0 or 1 is 1
    if (n <= 1) {
        return 1;
    }
    // Recursive case: n! = n * (n-1)!
    return n * factorial(n - 1);
}

Call Stack

Stack is empty

Execution Trace

Speed:
Step 1 of 0
Time: O(n)
Space: O(n) - call stack
Understanding the Call Stack Memory

Each recursive call creates a new stack frame in memory:

← Stack grows downward
factorial(4)
n = 4, waiting for factorial(3)
factorial(3)
n = 3, waiting for factorial(2)
factorial(2)
n = 2, waiting for factorial(1)
factorial(1) ← Currently executing
n = 1, base case! returns 1
  • Each frame stores its own copy of parameters and local variables
  • Frames are created on function call and destroyed on return
  • Too many frames = StackOverflowError!
Key Takeaways

Stack Grows Then Shrinks

Each call adds a frame. When base case is hit, frames start returning and popping off the stack.

Returns Happen in Reverse

The deepest call returns first (LIFO - Last In, First Out). Results bubble up through the call chain.