BETA Try the new lesson view
Code

A week of temperatures

The first program with an array: a week of temperatures.

Create practice/06:

add_executable(p06_temperatures main.c)
target_link_libraries(p06_temperatures PRIVATE course_input)

main.c:

  • #define DAYS 7: the array's size in one place.
  • void read_temperatures(int t[], int n): fills the array, t[i] = read_int(...). Before the question, printf("%d. ", i + 1): people count days from 1, the array from 0.
  • void print_array(const int t[], int n): prints the values on one line. The space is written before every value except the first, so no space is left at the end of the line.
  • double average(const int t[], int n): a sum with a loop, then (double)sum / n.
  • main declares the array int temperatures[DAYS]; and passes it to the functions together with its size.

Every function has a contract and an assert, as in topic 5: n must fit in the array.

read_temperatures changes the array, so its parameter has no const. print_array and average only read it: they get const.

Run it

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

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

Commit: Store temperatures in array.