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 casen <= 1(notn == 1— this keepsfactorial(0)safe too), recursive casen * factorial(n-1).factorialLoop— the same job with a plainforloop: shorter, no growing stack.
Verify — go 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 offactorial(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 overflowMemorize this message —
stack overflowalmost always means recursion without a working base case. The base case must (a) exist and (b) be reachable — every call must shrink the task. Putn-1back and confirm it works again.