Walk an Array of Records
Tape and glue sit in separate bins, but the desk needs one total. bins[i] picks a record from the array; .units picks the count in that record. For two bins, the valid indexes are 0 and 1.
c
#include <stdio.h>
struct Bin {
const char *item;
int units;
};
int main(void) {
struct Bin bins[] = {{"Tape", 2}, {"Glue", 5}};
int total = 0;
for (int i = 0; i < 2; i++)
total += bins[i].units;
printf("Units: %d\n", total);
return 0;
}
The outer braces initialize the array; each inner pair initializes one struct Bin. Trace the loop before Run: index 0 adds 2 to total, then index 1 adds 5. The result is Units: 7. i < 2 stops before the invalid index 2. If the glue count were 6 instead, the same loop would total 8.