Skip to the task
Layout
Back to classic view

You are looking at lesson 5. Your place is still lesson 10, task 1: struct.

CREATETask 10 of 23 · step 5: RecursionCreate recursion.c
Create recursion.c in practice/05/

Two recursive functions with contracts: digit_sum with a depth, and factorial.

Checklist

  • Every task is one commit with a clear message.
  • Zero compiler warnings: the code builds with -Werror.
  • Once per topic you step through your code in the debugger (CLion, gdb).
  • Every function has preconditions and postconditions, and assert tests check them.

Numbered notes in the code explain the important lines.

Details & hint
  • digit_sum(int n, int depth): the base case n < 10, otherwise n % 10 + digit_sum(n / 10, depth + 1). printf("%*s...", depth * 2, "", ...) writes depth * 2 spaces before the name.
  • factorial(int n): the base case n == 0 → 1, otherwise n * factorial(n - 1). The precondition is n >= 0 && n <= 20.

Stuck? %lld prints a long long. With %d the compiler reports format '%d' expects argument of type 'int'.

practice 05 recursion.c Code Diff +34
A · NEW FILE Create this file. Every line is new: see the green bar.
#include <assert.h>
#include <stdio.h>
/* The digit sum; depth is how many calls deep the function already is.
Before: n >= 0, depth >= 0.
After: the sum of the digits of n. */
int digit_sum(int n, int depth) {
assert(n >= 0 && depth >= 0);
printf("%*sdigit_sum(%d)\n", depth * 2, "", n);
Note 1: The width comes from an argument: depth * 2 spaces.
if (n < 10) {
Note 2: The base case: answered at once, no recursion.
return n;
}
return n % 10 + digit_sum(n / 10, depth + 1);
Note 3: The recursive case: a smaller piece of the same problem.
}
/* n! = 1 * 2 * ... * n.
Before: n is from 0 to 20 (21! doesn't fit in a long long).
After: the factorial of n; 0! = 1. */
long long factorial(int n) {
assert(n >= 0 && n <= 20);
Note 4: 21! doesn't fit in a long long, hence the limit 20.
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main(void) {
int sum = digit_sum(472, 0);
printf("Digit sum: %d\n", sum);
printf("5! = %lld\n", factorial(5));
printf("20! = %lld\n", factorial(20));
return 0;
}