Learn C · lesson 50 of 60 · about 9 minutes
Recursion on Arrays and Strings
Handle one item, then let a recursive call handle the rest.
What you'll learn
- Recurse over an array with an index or a length
- Recurse over a string until its null terminator
- Choose the right stopping point
The load check
Before the restart, the report checks how busy the servers are. The admin types how many servers there are, then each one's load in percent, and the report sums them up: 4 servers: average load 56%, peak 90%. Two recursive functions do the work on the array of loads: total_load adds the last load to the total of the ones before it, and peak_load keeps the bigger of the last load and the peak of the ones before it. Both pass the array and a length that gets one smaller each call.
Arrays: one item and the rest
C can't make a smaller copy of an array cheaply, so recursive functions pass the length instead. The total of the first n items is the last item, a[n - 1], plus the total of the first n - 1.
The base case is n == 0: the total of no items is 0.
Adding up an array
#include <stdio.h>
int total(const int a[], int n) {
if (n == 0) return 0;
return a[n - 1] + total(a, n - 1);
}
int main(void) {
int nums[] = {4, 1, 5, 2};
printf("%d\n", total(nums, 4));
return 0;
}Output
12Strings: stop at the null terminator
A string ends with '\0'. A recursive string function looks at *s, the first character, and passes s + 1, a pointer to the rest. When *s is '\0', the string is used up.
Length and backwards printing
#include <stdio.h>
int length(const char *s) {
if (*s == '\0') return 0;
return 1 + length(s + 1);
}
void backwards(const char *s) {
if (*s == '\0') return;
backwards(s + 1);
putchar(*s);
}
int main(void) {
printf("%d\n", length("phoebe"));
backwards("phoebe");
printf("\n");
return 0;
}Output
6
ebeohpA different base case for the peak
Not every question has an answer for no items at all. The total of no loads is 0, but there's no peak among none. So peak_load stops at one load, n == 1, whose peak is itself, and the report only calls it when at least one load was read.
Tip
For flat arrays, a loop is usually simpler. Recursion shines when a problem naturally splits into smaller copies of itself, like the puzzle in this unit's project.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.