< Previous | Contents | Next >

Indexing Arrays

You index arrays much like you index string objects. You can access any individual element by providing an index number with the subscripting operator ([]).

Next, I add three items to the heros inventory using the subscripting operator:

int numItems = 0; inventory[numItems++] = "sword"; inventory[numItems++] = "armor"; inventory[numItems++] = "shield";

I start by defining numItems for the number of items the hero is carrying at the moment. Next I assign "sword" to position 0 of the array. Because I use the postfix increment operator, numItems is incremented after the assignment to the array. The next two lines add "armor" and "shield" to the array, leaving numItems at the correct value of 3 when the code finishes.

Now that the hero is stocked with some items, I display his inventory:

cout << "Your items:\n";

for (int i = 0; i < numItems; ++i)

100 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble



{

cout << inventory[i] << endl;

}

This should remind you of string indexing. The code loops through the first three elements of inventory, displaying each string object in order.

Next, the hero trades his sword for a battle axe. I accomplish this through the following line:

inventory[0] = "battle axe";

The previous code reassigns the element at position 0 in inventory with the string object "battle axe". Now the first three elements of inventory are "battle axe", "armor", and "shield".


Tra p

image

Array indexing begins at 0, just as you saw with string objects. This means that the following code defines a five-element array:

int highScores[5];

Valid position numbers are 0 through 4, inclusive. There is no element highScores[5]! An attempt to access highScores[5] could lead to disastrous results, including a program crash.

image