Recursion in C
A base case and a smaller problem, on the stack rather than in a loop.
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int sum_digits(int n) {
if (n < 10) {
return n;
}
return n % 10 + sum_digits(n / 10);
}
int ackermann_lite(int m, int n) {
if (m == 0) {
return n + 1;
}
return ackermann_lite(m - 1, 1);
}
How it works
- The base case is what stops the recursion.
- Each call gets its own copy of the locals.
- Deep recursion costs stack, so C often prefers the loop.
Keywords and builtins used here
ackermann_litefactorialifintreturnsum_digits
The run, in numbers
- Lines
- 20
- Characters to type
- 269
- Tokens
- 96
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 64 seconds.
Step 6 of 7 in Functions, step 20 of 35 in Language basics.