C Recursion
Recursion is a function calling itself on a smaller piece of the same job. A base case stops the chain, and without one the calls never stop.
Count down by calling again
count_down prints 3, then calls itself on 2, then on 1. At 0 it prints Done and stops, so the output ends there.
#include <stdio.h>
void count_down(int n) {
if (n == 0) {
printf("Done!\n");
return;
}
printf("%d\n", n);
count_down(n - 1);
}
int main() {
count_down(3);
return 0;
}Factorial with recursion
Factorial of 0 is 1, and that is the base case. Trace factorial(4) by hand: it waits on factorial(3), which waits on factorial(2), then factorial(1), then factorial(0), and 1 travels back up the chain to make 24.
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
printf("%d\n", factorial(4));
return 0;
}Add up the numbers
sum_to adds a number to the sum of all the numbers below it. The sum of 0 is 0, and that base case ends the chain at 15.
#include <stdio.h>
int sum_to(int n) {
if (n == 0) {
return 0;
}
return n + sum_to(n - 1);
}
int main() {
printf("%d\n", sum_to(5));
return 0;
}Example
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
printf("%d\n", factorial(3));
printf("%d\n", factorial(5));
return 0;
}Key points
- A recursive function is a function that calls itself.
- Each call must take on a smaller piece of the job.
- The base case is the smallest piece, and it gives an answer with no new call.
- Without a base case, the calls would never stop.
- A countdown prints a number and then calls itself on the number below it.
- Factorial of a number is the number times the factorial below it.
- The chain of calls ends when the number reaches the base case.
factorial calls itself on the number below it each time, until the number reaches 0. The factorial of 3 is 6, so 6 prints first. The factorial of 5 is 120, so 120 prints next.
Note
A big starting number makes a very long chain of calls.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What stops a recursive function from calling itself forever?