Skip to main content

Report Pipeline Repair

Challenge on lesson: Checkpoint: Debugging

Fix all three defects in the pipeline below: (1) avg must not use integer division, (2) max_of must handle n == 1 correctly (start from a[0]), (3) report(const int *a, int n, char *out) must write n=<n> avg=<g> max=<g> into out with snprintf (%g for the doubles). Reference: report({2, 4}, 2, buf) makes buf n=2 avg=3 max=4. ``c double avg(const int *a, int n) { int s = 0; for (int i = 0; i < n; i++) s += a[i]; return s / n; /* BUG: integer division */ } int max_of(const int *a, int n) { int m; for (int i = 1; i < n; i++) if (a[i] > m) m = a[i]; /* BUG: m uninitialized */ return m; } void report(const int *a, int n, char *out) { printf("n=%d avg=%g max=%g\n", n, avg(a, n), (double)max_of(a, n)); /* BUG: prints, ignores out */ } ``

Difficulty: beginner

Back to lesson: Checkpoint: Debugging