Lesson contents

C — Counting keys with arrays

In C, two arrays can form a small lookup table. Find a key with strcmp, then use the same index in the second array to read or increment its count.

A simple example

Look up one count

  1. Start with Key A has value 2
  2. Do this Look up A
  3. Result 2
The key identifies which stored value to read.
lesson.c
#include <stdio.h>

int main(void) {
    struct Count { char key; int value; };
    struct Count counts[] = {{'A', 2}};
    if (counts[0].key == 'A') {
        printf("%d\n", counts[0].value);
    }
}
Output
2
Advertisements

Count labels without relying on storage order

Each count is stored at the same index as its corresponding key. strcmp returns zero for equal strings. This small fixed vocabulary is simple to inspect. An unknown key is ignored.

Scan order: Red, blue, red. Red team: 2 wristbands. Blue team: 1 wristband.
Count team wristbands

A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.

Run the example

C17. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 lesson.c -o lesson
./lesson
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *colors[] = {"red", "blue", "red"};
    const char *keys[] = {"red", "blue"};
    int counts[] = {0, 0};
    for (size_t i = 0; i < sizeof colors / sizeof colors[0]; ++i) {
        for (size_t k = 0; k < sizeof keys / sizeof keys[0]; ++k) {
            if (strcmp(colors[i], keys[k]) == 0) {
                ++counts[k];
                break;
            }
        }
    }
    for (size_t k = 0; k < sizeof keys / sizeof keys[0]; ++k) {
        printf("%s %d\n", keys[k], counts[k]);
    }
    return 0;
}
Output
red 2
blue 1

The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.

Try it yourself

Insert another blue before the last red. What changes?

Check your answer

Both keys now have a count of two. The requested display order stays red, then blue.

GNU C Language Manual

Related tags

  • C
  • collections
  • frequency counts
  • lookup