Example 1 — Order total from an array of items
Loop over records, print each line total, and sum them.
#include <stdio.h>
struct Item {
const char *name;
double price;
int qty;
};
int main(void) {
struct Item items[] = {
{"Pen", 1.5, 10},
{"Book", 12.0, 2},
{"Bag", 25.0, 1}
};
int n = sizeof items / sizeof items[0];
double total = 0;
for (int i = 0; i < n; i++) {
double line = items[i].price * items[i].qty;
printf("%-5s x%d = %.2f\n", items[i].name, items[i].qty, line);
total += line;
}
printf("Total: %.2f\n", total);
return 0;
} How It Works
- Each element is a complete
struct Item. %-5sleft-aligns names in five columns.- 15 + 24 + 25 = 64.
