Sensor data: sum, average, minimum, maximum
Computing with an array of readings: the sum accumulator, the average with a cast, minimum and maximum from the first element, counting by a rule and counting occurrences, changes between neighbours, linear search, an array as a function parameter, a first sorting pass, and how to test it all. Prepares lab experiments 10 and 17.
The job
A test rig has ten ADC channels. The program must read the ten readings, keep them in one array, and report statistics: the sum, the average, the minimum, the maximum, and counts. Every program in this lesson follows the same four stages:
- Acquire: read the channels.
- Store: keep them in one array.
- Analyze: compute sums and extremes.
- Report: print the statistics and counts.
This is exactly what lab experiments 10 (ten integers: sum, average, maximum, minimum) and 17 (thirteen integers: maximum and how often, minimum and how often, average with three decimals) ask for. The examples use the five readings from the previous lesson:
#define LENGTH 5
int readings[LENGTH] = {412, 398, 405, 421, 399};The sum accumulator
An accumulator (צובר) is a variable that collects a total as the loop runs:
int sum = 0;
for (int i = 0; i < LENGTH; i++) {
sum = sum + readings[i];
}Two rules make it correct. sum starts at 0, because adding 0 changes nothing. And every element is added exactly once: skip one, or add one twice, and the sum is wrong. Here is the trace for the four values {4, 7, 2, 5}:
| i | readings[i] | sum |
|---|---|---|
| start | 0 | |
| 0 | 4 | 0 + 4 = 4 |
| 1 | 7 | 4 + 7 = 11 |
| 2 | 2 | 11 + 2 = 13 |
| 3 | 5 | 13 + 5 = 18 |
The average keeps the fraction
sum and LENGTH are both int. Dividing two int values gives an int: the fraction is thrown away before the result is stored.
double average = sum / LENGTH; /* 55 / 10 is 5, then 5.000 */
double average = (double)sum / LENGTH; /* 55.0 / 10 is 5.5 */The cast (המרת טיפוס) (double)sum turns sum into a double before the division, so the division keeps the fraction. Print it with %.3f for three decimals: 5.500. The division also needs LENGTH to be greater than 0, which is a precondition (תנאי מקדים) of the code.
Minimum and maximum start from the first element
Start both extremes from a real reading, readings[0], then compare the rest. Because index 0 is already used, the loop starts at 1:
int minimum = readings[0];
int maximum = readings[0];
for (int i = 1; i < LENGTH; i++) {
if (readings[i] < minimum) {
minimum = readings[i];
}
if (readings[i] > maximum) {
maximum = readings[i];
}
}A variable changes only when the current element proves a new extreme:
| i | readings[i] | minimum | maximum |
|---|---|---|---|
| start | 412 | 412 | 412 |
| 1 | 398 | 398 | 412 |
| 2 | 405 | 398 | 412 |
| 3 | 421 | 398 | 421 |
| 4 | 399 | 398 | 421 |
Counting values that match a rule
How many readings are at or above 410?
int high_count = 0;
for (int i = 0; i < LENGTH; i++) {
if (readings[i] >= 410) {
high_count++;
}
}The answer is 2 (412 and 421). A reading of exactly 410 would count too, because the rule is >=. Notice the two different counters: i counts the positions visited (it always reaches 5), high_count counts the values that match. They cannot be the same variable. The array itself does not change.
How many times does a value occur?
The same pattern with == counts the occurrences (הופעות) of a target value:
int occurrences = 0;
for (int i = 0; i < LENGTH; i++) {
if (readings[i] == target) {
occurrences++;
}
}Test it with a target that is absent (0), present once (1), repeated (the exact count), and an array where every element equals the target (LENGTH).
Changes between neighbours
To print the change between each sample and the one before it, compare data[i] with data[i - 1]. The first element has no previous element, so the loop starts at 1:
int data[LENGTH] = {12, 18, 15, 21, 17};
for (int i = 1; i < LENGTH; i++) {
int change = data[i] - data[i - 1];
printf("%d\n", change);
}6
-3
6
-4Starting at 0 would read data[-1], outside the array. The same pattern checks whether an array is sorted: every element must be at least the one before it.
Linear search
A linear search (חיפוש לינארי) checks the elements in order and stops at the first match:
int found = -1;
for (int i = 0; i < LENGTH; i++) {
if (data[i] == target) {
found = i;
break;
}
}With target 21, the loop checks 12, 18, 15, then finds 21 at index 3. found becomes 3 and break leaves the loop; index 4 is never visited. If the target is not there, found stays -1. We use -1 for "not found" because -1 can never be a valid index. Use break only when the task asks for the first match.
An array as a function parameter
A function can receive an array. It also needs the length, because it cannot see how long the array is:
int sum_array(const int data[], int length)
{
int sum = 0;
for (int i = 0; i < length; i++) {
sum += data[i];
}
return sum;
}The contract: data supplies the elements, length supplies the safe bound, const promises that the function will not change the array, and return supplies the sum. The call sum_array(readings, LENGTH) returns 2035. Always pass the length with the array; the details of how arrays are passed come with pointers, later in the course.
A complete program
The five readings, all the statistics of this lesson in one program:
#include <stdio.h>
#define LENGTH 5
int sum_array(const int data[], int length);
int main(void)
{
int readings[LENGTH] = {412, 398, 405, 421, 399};
int sum = sum_array(readings, LENGTH);
double average = (double)sum / LENGTH;
int minimum = readings[0];
int maximum = readings[0];
for (int i = 1; i < LENGTH; i++) {
if (readings[i] < minimum) {
minimum = readings[i];
}
if (readings[i] > maximum) {
maximum = readings[i];
}
}
int high_count = 0;
for (int i = 0; i < LENGTH; i++) {
if (readings[i] >= 410) {
high_count++;
}
}
printf("SUM %d\n", sum);
printf("AVG %.3f\n", average);
printf("MIN %d\n", minimum);
printf("MAX %d\n", maximum);
printf("HIGH %d\n", high_count);
return 0;
}
int sum_array(const int data[], int length)
{
int sum = 0;
for (int i = 0; i < length; i++) {
sum += data[i];
}
return sum;
}SUM 2035
AVG 407.000
MIN 398
MAX 421
HIGH 2A first look at sorting
Sorting puts the values in order. The simplest idea: walk the array once, compare each pair of neighbours, and swap them if they are out of order. One pass over 7 3 6 2:
| compare | swap? | array after |
|---|---|---|
| 7 and 3 | yes | 3 7 6 2 |
| 7 and 6 | yes | 3 6 7 2 |
| 7 and 2 | yes | 3 6 2 7 |
After one pass the largest value has reached the end. More passes finish the sort. This is bubble sort; the full algorithm and its efficiency are in unit 10.
Debugging: four faults
This program should read five values and print their sum. It has four faults:
int values[5];
int sum;
for (int i = 1; i <= 5; i++) {
scanf("%d", values[i]);
sum += values[i];
}
printf("%d\n", sum);Testing array programs
One test is never enough. The acceptance tests for the ten-channel program each target a different bug:
| Input | Sum | Average | Minimum | Maximum | Checks |
|---|---|---|---|---|---|
1 2 3 4 5 6 7 8 9 10 | 55 | 5.500 | 1, once | 10, once | the normal path |
7 7 7 7 7 7 7 7 7 7 | 70 | 7.000 | 7, ten times | 7, ten times | starting values and ties |
-5 0 5 -5 5 0 -5 5 0 0 | 0 | 0.000 | -5, three times | 5, three times | negatives and zero |
Also test an extreme at index 0 and one at the last index: it proves that the loop visits every element.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| accumulator | צובר | a variable that collects a total, starts at 0 |
| average | ממוצע | (double)sum / LENGTH |
| cast | המרת טיפוס | (double)x changes the type of a value |
| minimum, maximum | מינימום, מקסימום | the smallest and the largest value; start from the first element |
| counter | מונה | a variable that counts the values that match |
| occurrence | הופעה | one place where a value appears |
| linear search | חיפוש לינארי | checking the elements in order until a match |
| adjacent elements | איברים סמוכים | data[i - 1] and data[i] |
| precondition | תנאי מקדים | something that must be true before the code runs |
| test case | מקרה בדיקה | an input and the output you expect |
Practice
More questions, with answers: Practice: arrays, questions 6 to 10, 13, 16 to 19 and 21 to 30, and Practice: traversal and strings, questions 39, 45 and 46.