A Small C Project: Packing Tool with Structs, Pointers, Functions and Loops (C Learning Guide, Part 9)

Every piece of the packing tool now works on its own: structures hold an order, functions do the work, pointers change a record and loops repeat the steps. A lab project or viva asks for all four in one program, and the jump from small examples to one complete tool is where many students lose marks. This part builds that tool in five stages.

This is Part 9 of the C Learning Guide. Part 8 covered structures, and this project reuses the same Order record. Every complete program below was compiled and run with gcc -Wall -Wextra -std=c17. The output blocks contain captured output, not predicted results.

Build the stages in order. Each one is a complete program you can compile on its own, and each adds exactly one idea to the same packing tool.

Stage 1: records and a loop

The tool starts with the data. One typedef names the Order record, an array holds a day's orders and a for loop walks the array. Nothing here is new on its own; this stage is the skeleton that every later stage grows from.

#include <stdio.h>
#include <stddef.h>
typedef struct {
    int id;
    int items;
    int capacity;
} Order;
int main(void) {
    Order day[] = {{101, 17, 6}, {102, 9, 4}, {103, 24, 5}};
    size_t count = sizeof day / sizeof day[0];
    for (size_t i = 0; i < count; ++i) {
        int full = day[i].items / day[i].capacity;
        int left = day[i].items % day[i].capacity;
        printf("order %d: %d items -> %d full boxes of %d, %d left over\n",
               day[i].id, day[i].items, full, day[i].capacity, left);
    }
    return 0;
}

Verified output:

order 101: 17 items -> 2 full boxes of 6, 5 left over
order 102: 9 items -> 2 full boxes of 4, 1 left over
order 103: 24 items -> 4 full boxes of 5, 4 left over

Three records, one loop, and the whole day's packing plan is printed. The weakness is that main does every job itself, and a calculation buried inside a loop is hard to reuse or test.

Stage 2: give each job to a function

A function with a return value is the right home for a calculation. plan_order takes one Order by value and returns a Plan, a small record that holds the capacity, the full boxes and the leftover. print_order owns one line of output, so main only loops, delegates and adds up the items.

#include <stdio.h>
#include <stddef.h>
typedef struct {
    int capacity;
    int full;
    int leftover;
} Plan;
typedef struct {
    int id;
    int items;
    int capacity;
} Order;
Plan plan_order(Order o) {
    Plan p = {o.capacity, 0, o.items};
    if (o.capacity > 0) {
        p.full = o.items / o.capacity;
        p.leftover = o.items % o.capacity;
    }
    return p;
}
void print_order(Order o) {
    Plan p = plan_order(o);
    printf("order %d: %d full boxes of %d, %d left over\n",
           o.id, p.full, p.capacity, p.leftover);
}
int main(void) {
    Order day[] = {{101, 17, 6}, {102, 9, 4}, {103, 24, 5}};
    size_t count = sizeof day / sizeof day[0];
    int total = 0;
    for (size_t i = 0; i < count; ++i) {
        print_order(day[i]);
        total += day[i].items;
    }
    printf("total items = %d\n", total);
    return 0;
}

Verified output:

order 101: 2 full boxes of 6, 5 left over
order 102: 2 full boxes of 4, 1 left over
order 103: 4 full boxes of 5, 4 left over
total items = 50

The same answers as stage 1, but the packing rule now lives in exactly one place. Change the rule once and every caller gets the new behaviour.

Stage 3: let a function change a record

Passing by value protects the original, but a real tool must also update records: a late addition to an order, a corrected count. find_order searches the array and returns a pointer to the matching record, or NULL when no order matches. add_items receives that pointer and changes the original record through ->.

#include <stdio.h>
#include <stddef.h>
typedef struct {
    int id;
    int items;
    int capacity;
} Order;
Order *find_order(Order *orders, size_t count, int id) {
    for (size_t i = 0; i < count; ++i) {
        if (orders[i].id == id) {
            return &orders[i];
        }
    }
    return NULL;
}
void add_items(Order *o, int extra) {
    if (o != NULL && extra > 0) {
        o->items += extra;
    }
}
int main(void) {
    Order day[] = {{101, 17, 6}, {102, 9, 4}, {103, 24, 5}};
    size_t count = sizeof day / sizeof day[0];
    Order *late = find_order(day, count, 102);
    if (late != NULL) {
        printf("found order %d with %d items\n", late->id, late->items);
        add_items(late, 6);
    }
    Order *missing = find_order(day, count, 999);
    printf("order 999 found: %s\n", missing != NULL ? "yes" : "no");
    for (size_t i = 0; i < count; ++i) {
        printf("order %d now holds %d items\n", day[i].id, day[i].items);
    }
    return 0;
}

Verified output:

found order 102 with 9 items
order 999 found: no
order 101 now holds 17 items
order 102 now holds 15 items
order 103 now holds 24 items

Only order 102 changed, because the function reached the original record through the pointer. Returning NULL for order 999 lets the caller decide what a missing order means instead of inventing one.

Stage 4: a tool that checks its data

Real data has mistakes. A capacity of zero would crash the tool with a division by zero, and a negative item count is nonsense. valid_order is the single gate: id positive, items zero or more, capacity positive. Every record passes through it before any division happens, and bad records are reported and skipped, never packed.

#include <stdio.h>
#include <stddef.h>
typedef struct {
    int capacity;
    int full;
    int leftover;
} Plan;
typedef struct {
    int id;
    int items;
    int capacity;
} Order;
int valid_order(Order o) {
    return o.id > 0 && o.items >= 0 && o.capacity > 0;
}
Plan plan_order(Order o) {
    Plan p = {o.capacity, 0, 0};
    if (valid_order(o)) {
        p.full = o.items / o.capacity;
        p.leftover = o.items % o.capacity;
    }
    return p;
}
void print_plan(Order o) {
    Plan p = plan_order(o);
    printf("order %d: %d items -> %d full boxes of %d, %d left over\n",
           o.id, o.items, p.full, p.capacity, p.leftover);
}
int main(void) {
    Order day[] = {{101, 17, 6}, {102, 9, 4}, {103, 24, 5}, {999, 7, 0}};
    size_t count = sizeof day / sizeof day[0];
    int total_items = 0;
    int total_boxes = 0;
    size_t used = 0;
    for (size_t i = 0; i < count; ++i) {
        if (!valid_order(day[i])) {
            printf("order %d skipped: bad data\n", day[i].id);
            continue;
        }
        print_plan(day[i]);
        Plan p = plan_order(day[i]);
        total_items += day[i].items;
        total_boxes += p.full + (p.leftover > 0);
        ++used;
    }
    printf("---\n");
    printf("orders packed = %zu, items = %d, boxes needed = %d\n",
           used, total_items, total_boxes);
    return 0;
}

Verified output:

order 101: 17 items -> 2 full boxes of 6, 5 left over
order 102: 9 items -> 2 full boxes of 4, 1 left over
order 103: 24 items -> 4 full boxes of 5, 4 left over
order 999 skipped: bad data
---
orders packed = 3, items = 50, boxes needed = 11

Order 999 has a zero capacity, so the tool refuses it and keeps going. The summary counts boxes honestly: an order with leftover items needs one more box than its full count alone.

Stage 5: the complete tool reads real orders

The last stage replaces the fixed array with input, so the tool packs any day's orders. The return value of scanf is checked before the values are trusted, the order count is limited to a sane range and every order still passes through valid_order. The packing rule itself does not change: the same functions from stages 2 to 4 do the work.

#include <stdio.h>
typedef struct {
    int capacity;
    int full;
    int leftover;
} Plan;
typedef struct {
    int id;
    int items;
    int capacity;
} Order;
int valid_order(Order o) {
    return o.id > 0 && o.items >= 0 && o.capacity > 0;
}
Plan plan_order(Order o) {
    Plan p = {o.capacity, 0, 0};
    if (valid_order(o)) {
        p.full = o.items / o.capacity;
        p.leftover = o.items % o.capacity;
    }
    return p;
}
void print_plan(Order o) {
    Plan p = plan_order(o);
    printf("order %d: %d items -> %d full boxes of %d, %d left over\n",
           o.id, o.items, p.full, p.capacity, p.leftover);
}
int main(void) {
    int wanted = 0;
    printf("how many orders? ");
    if (scanf("%d", &wanted) != 1 || wanted <= 0 || wanted > 100) {
        printf("no valid order count; nothing to pack\n");
        return 1;
    }
    int total_items = 0;
    int total_boxes = 0;
    int packed = 0;
    for (int i = 0; i < wanted; ++i) {
        Order o = {0, 0, 0};
        printf("order %d (id items capacity): ", i + 1);
        if (scanf("%d %d %d", &o.id, &o.items, &o.capacity) != 3) {
            printf("bad input; stopping\n");
            return 1;
        }
        if (!valid_order(o)) {
            printf("order %d skipped: bad data\n", o.id);
            continue;
        }
        print_plan(o);
        Plan p = plan_order(o);
        total_items += o.items;
        total_boxes += p.full + (p.leftover > 0);
        ++packed;
    }
    printf("---\n");
    printf("orders packed = %d, items = %d, boxes needed = %d\n",
           packed, total_items, total_boxes);
    return 0;
}

Verified output:

how many orders? order 1 (id items capacity): order 101: 17 items -> 2 full boxes of 6, 5 left over
order 2 (id items capacity): order 102: 9 items -> 2 full boxes of 4, 1 left over
order 3 (id items capacity): order 999 skipped: bad data
---
orders packed = 2, items = 26, boxes needed = 6

Sample input for the runner and for trying it yourself: 3 on the first line, then one order per line as id, items, capacity: 101 17 6, 102 9 4, 999 7 0.

Order 999 is skipped exactly as it was in stage 4, and the summary reports the two real orders. This is the complete packing tool: structures for the data, functions for the work, pointers where records change, loops for the repetition and validation at every entry point.

What was checked, and what comes next

All five complete programs compiled without warnings using gcc with -Wall -Wextra -std=c17, then ran to produce the output shown. Each stage has an on-demand code runner; opening it loads the exact stage, and execution is a separate choice. Next: dynamic memory with malloc and free, so the tool can hold any number of orders without a fixed array or a 100-order limit.

Continue with the series index, revisit Part 8: structures, or use the Online Compiler.

Sources and scope

These examples use C17 on Linux. No padding value or member-layout assumption is needed to reproduce their output. The runner uses OneCompiler: code runs on its servers and its cookies/privacy policy apply. Do not enter secrets.

Comments

Popular posts from this blog

Big Data Analytics Exam Prep

Process States in OS: Diagram, PCB and Context Switching

Python Mutable Default Arguments and Shallow Copies: Why Lists Keep Changing