# C++ Notes: Struct Example 2

## Problem - Product info

Let's use the Product struct, read into an array of Products, and sort by increasing price.

## Global Declaration

Typically types are used in more than one function, and are therefore global or defined in an include file.

    struct Product {
        char mfg_id[4];    // 4 char code for the manufacturer.
        char prod_id[8];   // 8-char code for the product
        int  price;        // price of the product in dollars.
        int  qty_on_hand;  // quantity on hand in inventory
    };

## Local Declarations

    Product prods[1000]; // array to hold up to 1000 products
    int n = 0;           // number of products in the array.

## Reading the input

    while (cin >> prods[n].mfg_id >> prods[n].prod_id
               >> prods[n].price  >> prods[n].qty_on_hand) {
        n++;
    }

## Sorting the array of products

Here's a simple bubble sort function that stops when there are no more exchanges. This is a fairly inefficient sort, and it's used here just as an example. Notice we can't compare the entire struct, only individual fields.

    void bubbleSort2(Product pd[], int size) {
        bool doMore;
        do {
            doMore = false;  // assume this is last pass over array
            for (int i=0; i<size-1; i++) {
                if (pd[i].price > pd[i+1].price) {
                    // exchange elements
                    Product temp = pd[i]; pd[i] = pd[i+1]; pd[i+1] = temp;
                    doMore = true;  // after exchange, must look again
                }
            }
        } while (doMore);
    }