/********************************************************************/ /* CS167 C Programming */ /* the wood screw inventory */ /* practice with functions as modules and as abstractions */ /* Roger Hartley, Spring 1998 */ /********************************************************************/ #include #define SIZE 5 /* the size of the inventory and cost arrays */ #define SENTINEL 9999 /* typed by the user as a screws size */ /* global constant array of costs (in dollars) of each screws size the array is ordered by screw size 4, 6, 8, 10, 12 */ const float screwCost[SIZE] = { 0.3, 0.35, 0.45, 0.5, 0.65 }; int calculateIndex(int size, int max) { /* there is a simple relationship between screw size and the array index */ int index = size / 2 - 2; /* if we are passed an invalid screw size, the index will also be invalid, so return -1 */ if (index < 0 || index >= max) return -1; else return index; } int calculateSize(int i) { /* the inverse of calulcateIndex - no checking is necessary, since this will never be passed an invalid index */ return (i + 2) * 2; } /* Update does the work of altering the qantity of screws on hand by adding the passed value (read from the user) to the quantity stored in the inventory array - this might be postiive(an increase) or negative (a decrease) */ void Update(int inv[], int arraySize, int screwSize, int screwQuant) { int index = calculateIndex(screwSize, arraySize); if (index != -1) inv[index] += screwQuant; else { printf("Sorry, the screw size you typed was invalid\n"); printf("the line will be ignored\n"); } } /* Input does the work of reading values from the user (screw size and quantity) in a loop, and passing the values to Update - the end of input is signified by typing 9999 as a screw size - note that a quantity must also be typed with the sentinel, but is ignored */ void Input(int inv[]) { int screwSize, screwQuant; printf("Type any number of lines, each with a screw size (4, 6, 8, 10 or 12)\n"); printf("and a quantity (+ or -), separated by a space\n"); scanf("%d%d", &screwSize, &screwQuant); while (screwSize != SENTINEL) { Update(inv, SIZE, screwSize, screwQuant); scanf("%d%d", &screwSize, &screwQuant); } } /* Print displays a table of sizes, quantity on hand, and the worth of the inventory of each screw size - it also accumulates the total worth of the whole inventory and displays this moneyamount */ void Print(int inv[], int size) { int i; int quant; float invCost, totalCost = 0.0; printf("%5s%6s%10s\n", "Size", "Quant", "Worth ($)"); for (i = 0; i < size; i++) { quant = inv[i]; invCost = quant * screwCost[i]; totalCost += invCost; printf("%5d%6d%10.2f\n", calculateSize(i), inv[i], invCost); } printf("\nTotal inventory worth is $%-10.2f\n", totalCost); } /* the main program just declares the inventory array, initializes it to all zeros, calls Input and Print */ int main() { int inventory[SIZE] = { 0 }; Input(inventory); Print(inventory, SIZE); }