| |
Main Menu | Next Section |
| Section III: Arrays and For Loops | Section I : Introducing Arrays | Section II: Accessing Array Elements | Section IV: Arrays as Parameters |
A. Initializing an Array
Many of the operations called for in this inventory program will
require us to do some operation on all the elements in the array.
For example, suppose we are about to open a new store and we want
to initialize the array for that store to indicate that no inventory
exists yet. In other words, we want to initialize all the array
elements to 0. We could write the code:
const int MAX_ITEMS = 10000;
int itemInventory[MAX_ITEMS];
for (int itemCode = 0; itemCode < MAX_ITEMS; itemCode++)
{
itemInventory[itemCode] = 0;
}
Now explore the loop defined by the 'for' statement. The first time
through the loop, the value of 'itemCode' is 0 and so the zero-th
element of the array is initialized to 0. Then 'itemCode' is incremented
to 1 and the single line inside the for statement causes the next
element to be initialized to 0. As the value of 'itemCode' is
continuously incremented, so are the elements in the array initialized
to 0. Finally, 'itemCode' reaches 9999, the 9999th element of
the array is initialized to 0, 'itemCode' is incremented to 10000,
and the for statement test (itemCode < MAX_ITEMS) becomes FALSE.
This signals the end of the loop with our goal met - every element
in the array has the value 0.
B. Arrays with Input and Output
We are looking at another pattern here.
Pattern Name:
Purpose:
Pattern:
int itemAmount;
for (int itemCode = 0; itemCode < MAX_ITEMS; itemCode++)
{
cout << "Please enter the inventory count for item: " << itemCode;
cin >> itemAmount;
itemInventory[itemCode] = itemAmount;
}
There really isn't much new inside the loop. We ask the user for
the correct inventory amount for an item, taking advantage of
the fact that 'itemCode' contains the code for the item under
consideration. We then wait for the user to enter the value and,
finally, store it in the correct element of the array.
We could even simplify this code and write:
for (int itemCode = 0; itemCode < MAX_ITEMS; itemCode++)
{
This code would have the same effect as the code above with the
input going directly into the array element as opposed to going
first to a local variable and then into the array element.
Similarly we could write:
for (int itemCode = 0; itemCode < MAX_ITEMS; itemCode++)
{
This will output the amount of each item in the inventory.
Note that as long as we have written the 'for' statement initialization and stopping conditions correctly, there is no reason to do any bounds checking here. The value for 'itemCode' cannot be less than 0 or greater than 9999.
| |
Main Menu | Next Section |