Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: Functions.

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

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.
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 04 main.c Code Diff
UNCHANGED This step does not change this file.
#include <stdio.h>
#include "input.h"
int main(void) {
int grade = read_int("Grade (0 - stop): ");
int sum = 0;
int count = 0;
while (grade != 0) {
sum += grade;
count++;
grade = read_int("Grade (0 - stop): ");
}
if (count > 0) {
printf("Average: %.2f\n", (double)sum / count);
} else {
printf("No grades.\n");
}
return 0;
}