90 min

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:

  1. Acquire: read the channels.
  2. Store: keep them in one array.
  3. Analyze: compute sums and extremes.
  4. 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}:

ireadings[i]sum
start0
040 + 4 = 4
174 + 7 = 11
2211 + 2 = 13
3513 + 5 = 18
One click per iteration: the pointer moves, the sum box changes and a new row appears in the trace table. Say the next total before you click.Open full screen

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:

ireadings[i]minimummaximum
start412412412
1398398412
2405398412
3421398421
4399398421
One click per iteration: the highlighted lines show which comparison changed a value. The min and max markers under the array show where the current extremes are.Open full screen

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.

The condition is tested at every position; only 412 and 421 make high_count grow.Open full screen

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).

The data is the third acceptance test, -5 0 5 -5 5 0 -5 5 0 0. Click a target and the loop runs again. Predict the count first.Open full screen

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
-4

Starting 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.

The search for 21: three failed comparisons, a match at index 3, and break.Open full screen

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 2

A 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:

compareswap?array after
7 and 3yes3 7 6 2
7 and 6yes3 6 7 2
7 and 2yes3 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.

One click per comparison: the pair is highlighted, then swapped. Ask how many passes the whole row needs.Open full screen

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:

InputSumAverageMinimumMaximumChecks
1 2 3 4 5 6 7 8 9 10555.5001, once10, oncethe normal path
7 7 7 7 7 7 7 7 7 7707.0007, ten times7, ten timesstarting values and ties
-5 0 5 -5 5 0 -5 5 0 000.000-5, three times5, three timesnegatives 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

EnglishHebrewMeaning
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.