Functions and Records
Recursion
Base Case and Unwinding
A recursive function calls itself with a smaller input. The base case stops the recursion; the recursive case combines the current value with the result of the next call. Each return resolves one frame on the way back out.
Program
Play the program to compute factorial(4) and watch the calls descend to the base case and unwind.
recursion.dart
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
void main() {
var result = factorial(4);
print(result);
}
base case
`if (n <= 1) return 1;` stops the recursion; without it the calls would never end.
recursive case
`n * factorial(n - 1)` calls the same function with a smaller argument.
unwinding
Each return resolves one frame: `factorial(2) = 2*1 = 2`, then `factorial(3) = 3*2 = 6`, then `factorial(4) = 4*6 = 24`.