Skip to the task
Layout
Back to classic view

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

CREATETask 4 of 28 · step 3: A week of temperaturesA week of temperatures in an array
A week of temperatures in an array in practice/06/

#define DAYS 7, the array temperatures and three functions: read_temperatures, print_array and average.

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
  • read_temperatures(int t[], int n) fills the array: before each question, printf("%d. ", i + 1).
  • print_array(const int t[], int n): a space before every value except the first.
  • average(const int t[], int n): a sum with a loop, then (double)sum / n.
  • Each function has a contract and assert(n >= 1 && n <= DAYS) (or n >= 0).

Stuck? A loop over an array goes from 0 while i < n. With i <= n the last pass would reach t[7], out of bounds.

practice 06 main.c Code Diff +52
A · NEW FILE git diff: every line is new (+52).
--- /dev/null
+++ b/practice/06/main.c
@@ -0,0 +1,52 @@
+ #include <assert.h>
+ #include <stdio.h>
+
+ #include "input.h"
+
+ #define DAYS 7
+
+ /* 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) {
+ assert(n >= 1 && n <= DAYS);
+ for (int i = 0; i < n; i++) {
+ printf("%d. ", i + 1);
+ 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) {
+ assert(n >= 0 && n <= DAYS);
+ for (int i = 0; i < n; i++) {
+ if (i > 0) {
+ 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];
+
+ read_temperatures(temperatures, DAYS);
+ printf("Temperatures: ");
+ print_array(temperatures, DAYS);
+ printf("Average: %.2f\n", average(temperatures, DAYS));
+ return 0;
+ }