Skip to the task
Layout
Back to classic view

You are looking at lesson 6. Your place is still lesson 7, task 1: Modules.

RUNTask 5 of 28 · step 3: A week of temperaturesRun it with a week of temperatures
Run it with a week of temperatures in practice/06/

File → Reload CMake Project, pick p06_temperatures and ▶. Type 3, -2, 5, 8, -1, 4, 6.

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
$ .\build\debug\practice\06\p06_temperatures.exe
1. Temperature: 3
2. Temperature: -2
3. Temperature: 5
4. Temperature: 8
5. Temperature: -1
6. Temperature: 4
7. Temperature: 6
Temperatures: 3 -2 5 8 -1 4 6
Average: 3.29

You should see: All seven values on one line and the average 3.29 (23 / 7).

practice 06 main.c Code Diff +52
A · NEW FILE Create this file. Every line is new: see the green bar.
#include <assert.h>
#include <stdio.h>
#include "input.h"
#define DAYS 7
Note 1: The size in one place: DAYS becomes 7 before compiling.
/* Reads n temperatures into the array t.
Before: 1 <= n <= DAYS.
After: t[0]..t[n - 1] are filled. */
void read_temperatures(int t[], int n) {
Note 2: The array isn't copied: what read_temperatures writes, main sees.
assert(n >= 1 && n <= DAYS);
for (int i = 0; i < n; i++) {
printf("%d. ", i + 1);
Note 3: Days from 1 for people, from 0 for the array.
t[i] = read_int("Temperature: ");
}
}
/* Prints n values of the array on one line, separated by a space.
Before: 0 <= n <= DAYS. */
void print_array(const int t[], int n) {
Note 4: const: the function won't change the array, and the compiler checks it.
assert(n >= 0 && n <= DAYS);
for (int i = 0; i < n; i++) {
if (i > 0) {
Note 5: A space before each but the first: none is left at the end.
printf(" ");
}
printf("%d", t[i]);
}
printf("\n");
}
/* The arithmetic mean.
Before: 1 <= n <= DAYS.
After: (t[0] + ... + t[n - 1]) / n. */
double average(const int t[], int n) {
assert(n >= 1 && n <= DAYS);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += t[i];
}
return (double)sum / n;
}
int main(void) {
int temperatures[DAYS];
Note 6: 7 int boxes in a row; until filled they hold garbage.
read_temperatures(temperatures, DAYS);
printf("Temperatures: ");
print_array(temperatures, DAYS);
printf("Average: %.2f\n", average(temperatures, DAYS));
return 0;
}
opened for this task
$ .\build\debug\practice\06\p06_temperatures.exe
1. Temperature: 3
2. Temperature: -2
3. Temperature: 5
4. Temperature: 8
5. Temperature: -1
6. Temperature: 4
7. Temperature: 6
Temperatures: 3 -2 5 8 -1 4 6
Average: 3.29