Recursion
A function can also call itself. That is recursion: a problem is solved through a smaller problem of the same kind.
Two cases
The digit sum of 472 = the last digit 2 + the digit sum of 47. And the digit sum of 47 = 7 + the digit sum of 4. And 4 has one digit already: its sum is the number itself.
int digit_sum(int n) {
if (n < 10) {
return n; /* the base case */
}
return n % 10 + digit_sum(n / 10); /* the recursive case */
}
- The base case is answered at once, without recursion. Without it the function would call itself forever.
- The recursive case calls itself with a smaller problem that gets closer to the base case: 472 → 47 → 4.
The call stack
Each call gets its own copy of n and waits until the inner call returns. Those waiting calls make up the call stack:
The stack is limited (about 2 MB with MinGW). Recursion without a base case overflows it, and the program crashes:
Process finished with exit code -1073741571 (0xC00000FD)
0xC00000FD is the Windows code for "stack overflow". Recursion fits when a problem naturally splits into a smaller one of the same kind. A simple calculation done 10 or 1000 times is done by a loop, with no risk to the stack.
recursion.c
A second program in the same folder. CMakeLists.txt gets one more target:
add_executable(p05_recursion recursion.c)
It doesn't need input.h: it asks nothing.
recursion.c has two recursive functions with contracts:
digit_sum(int n, int depth)is as above, with a second parameterdepth: how many calls deep the function already is.printf("%*s...", depth * 2, "", ...)writesdepth * 2spaces before the name, so you see the calls going deeper. (%*s: the width is taken from an argument.)factorial(int n): n! = n · (n − 1)!, and 0! = 1. The precondition isn <= 20, because 21! no longer fits in along long.
Run it
Pick p05_recursion and ▶:
digit_sum(472)
digit_sum(47)
digit_sum(4)
Digit sum: 13
5! = 120
20! = 2432902008176640000
Remove the base case
Delete the lines if (n == 0) { return 1; } from factorial and run it:
Assertion failed: n >= 0 && n <= 20, file C:/.../practice/05/recursion.c, line 20
Process finished with exit code 3
Without the base case factorial(0) calls factorial(-1), and the precondition catches it at once, before the stack overflows. Put the base case back.
Commit: Add recursion.