Library contents

C Lookup with a fallback count

Display a fallback stock count for an item missing from the ledger.

A simple example

Lookup with a fallback count

  1. Start with Map with A = 2
  2. Do this Read missing B with fallback 0
  3. Result 0
The lookup supplies zero because B has no stored value.

Syntax

C syntax
strcmp(stock[i].name, requested) == 0
Run these examples in C

Save one example at a time as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Show a balance for an item never received

A kiosk receives its first delivery of pencils but has yet to receive any rulers. Its stock display should show zero for rulers while keeping the ledger limited to products actually received.

From the programstruct Stock stock[] = {{"Pencil", 12}}
Result0 on hand, 1 product
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    struct Stock { const char *name; int quantity; };
    struct Stock stock[] = {{"Pencil", 12}};
    size_t used = sizeof stock / sizeof stock[0];
    int on_hand = 0;
    for (size_t i = 0; i < used; ++i) {
        if (strcmp(stock[i].name, "Ruler") == 0) {
            on_hand = stock[i].quantity;
            break;
        }
    }
    printf("%d on hand, %zu product", on_hand, used);
    return 0;
}
Output
0 on hand, 1 product

The display shows zero for rulers. The original pencil entry is still the only product in the ledger.

Advertisements

Look up a borrowed tripod

The equipment desk has a two-day loan period for a camera, but no special period for a tripod. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Giventripod missing · default 7 days
Worked result7

Read a room preference

The timetable stores a room choice for the choir club. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Givenchoir → Hall · default Studio
Worked resultHall

What to watch for

Scanning a small array of records is a C lookup pattern. Initialize the fallback before scanning and stop at a match.

Documentation for Lookup with a fallback count