Code

Write factorial — recursion and the loop side by side

For this experiment leave your app alone — make a separate folder (mkdir recursion, inside it go mod init recursion) and create main.go.

Both variants side by side — step 1's paper trace, as code:

  • factorial — recursive: base case n <= 1 (not n == 1 — this keeps factorial(0) safe too), recursive case n * factorial(n-1).
  • factorialLoop — the same job with a plain for loop: shorter, no growing stack.

Verifygo run . must print exactly:

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
loop says: 120

Both roads give 120 — only the road differs.

Gotcha. Delete the base case (or forget to shrink — write factorial(n) instead of factorial(n-1)) and run it. The calls have nowhere to stop, the stack grows until Go gives up:

runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow

Memorize this message — stack overflow almost always means recursion without a working base case. The base case must (a) exist and (b) be reachable — every call must shrink the task. Put n-1 back and confirm it works again.