Arrays are just a group of variables that are accessed through the same name.
This example is a little confusing because you actually have a 2D array of chars instead of a 1D array of strings which would be simpler and easier for a beginner to understand.... (but you can ignore me here... I have beef with the way a lot of C++ books are written and/or how the language is taught in general).
So I'm going to use a slightly different example that might be easier for you to understand:
1 2 3 4 5 6 7 8
|
int array[5] = { 6, 10, 15, 1, 30 };
cout << "index 2 is " << array[2] << endl;
for(int j = 0; j < 5; ++j)
{
cout << array[j] << endl;
}
|
outputs:
index 2 is 15
6
10
15
1
30 |
In this example we have an array of ints. The array is of size '5' as illustrated by the number in the brackets:
This means we actually have 5 different ints. Each int is considered an "element" of the array.
You can treat these elements just as you would if they were 5 individual variables. The way you choose which of the 5 vars you want to access is you specify an "index". Indexes start at 0 and count up... so
array[0]
would be the first element in the array,
array[1]
would be the one after that... etc etc... up until
array[4]
which is the last element in the array.
Therefore this line:
|
cout << "index 2 is " << array[2] << endl;
|
Prints "index 2 is 15" because it's accessing the 'index 2' element in the array... which was 15.
but we don't need to use a fixed value for that. Saying
array[2]
is fine.. but we can also use another variable to index the array. Which is what is done in the following for loop:
|
for(int j = 0; j < 5; ++j)
|
Let's start with how this for loop actually works. 'j' will start at 0, the loop body will run, then it will be incremented to 1, then the loop body runs again, etc, etc until
j < 5
becomes false. This means the body of the loop will run exactly 5 times:
once when j==0
once when j==1
once when j==2
once when j==3
once when j==4
Since j is different each time the loop body is run... we can use it as an index to our array to print each element:
1 2 3
|
{
cout << array[j] << endl;
}
|
The first time this loop body runs... j==0, so this will print array[0]... which is 6.
The next time, j==1, so this will print array[1]... which is 10.
etc
etc