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
- Start with Key A has value 2
- Do this Look up A
- Result 2
#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);
}
}
2
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.
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
#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;
}
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.