factorial(0) = 1, otherwise factorial(n) = n * factorial(n - 1). The smallest example of recursion with a single base case, used to visualise the call stack growing on descent and shrinking on unwind.

Algorithm

Basic Implementation

basic.f90
module factorial_mod
    implicit none
contains
    recursive function factorial(n) result(r)
        integer, intent(in) :: n
        integer :: r
        if (n == 0) then
            r = 1
        else
            r = n * factorial(n - 1)
        end if
    end function factorial
end module factorial_mod

program recursion_factorial
    use factorial_mod
    implicit none
    integer :: result
    result = factorial(5)
    print '(I0)', result
end program recursion_factorial

The pinned run is factorial(5). The diagrams separate the descent, the base case, and the return values so the stack does not feel invisible.

Step 1 - Descend to the base case

Each call waits for one smaller call until f(0) returns 1.

Call tree for factorial(5): f(5) waits on f(4), down to f(0).f(5)waitsf(4)waitsf(3)waitsf(2)waitsf(1)waitsf(0)base = 1

Step 2 - Base value starts the unwind

The first finished frame is f(0) = 1; f(1) can now compute 1 * 1.

Call stack just before unwind begins.top -> bottomknown returnf(0)1f(1)waitingf(2)waitingf(3)waitingf(4)waitingf(5)waiting

Step 3 - Unwind returns 120

Each frame multiplies its n by the completed smaller result.

Return chain for factorial(5).framecalculationreturnsf(0)base1f(1)1 * 11f(2)2 * 12f(3)3 * 26f(4)4 * 624f(5)5 * 24120

Complexity

  • Time: O(n)
  • Space: O(n) call stack

Implementation notes

  • Fortran: the helper must be declared recursive function factorial(n) result(r) so the compiler permits self-calls. The result variable must be distinct from the function name to avoid the assumed-result alias.
  • The replay shows the call-stack contents on each frame and the computed n * factorial(n-1) value on each unwind, matching the lesson spec.
descend then unwind Each non-base call awaits the result of the next call, then multiplies.