An array is a group of variables that share a name.
Here's an example:
1 2 3 4 5
|
int billy0 = 16;
int billy1 = 2;
int billy2 = 77;
int billy3 = 40;
int billy4 = 12071;
|
Here, we have 5 different variables, each with a unique value. You could do something like this:
int foo = billy1 + billy2; // foo == 79
Arrays let you do the same thing, but instead of having to give a unique name for each variable, they all share the same name. Instead, they have a unique "index":
1 2 3 4 5 6 7 8 9 10
|
int billy[5]; // an array of 5 ints
int billy[0] = 16; // index 0 is set to 16
int billy[1] = 2; // index 1 is set to 2, etc
int billy[2] = 77;
int billy[3] = 40;
int billy[4] = 12071;
int foo = billy[1] + billy[2]; // foo == 79
|
The thing that makes arrays useful is that you can use a variable to specify the index. So you can do something like this:
1 2
|
int index = 3;
int foo = billy[ index ]; // billy[index] == billy[3] == 40
|
The for loop you posted simply uses 'n' as an index. 'n' counts from 0 to 4, allowing you to access each individual "element" in the array.
For loops operate like so:
1 2 3 4
|
for( initialization; condition; iteration )
{
body;
}
|
1) 'initialization' is done once at loop start.
2) 'condition' is checked. If it's true, continue to step 3. Otherwise, exit the loop.
3) 'body' is executed
4) 'iteration' is executed
5) goto step 2
So with this simple loop:
1 2 3 4
|
for (n=0; n<5; n++)
{
result += billy[n];
}
|
Here, the loop body will run 5 times. The first time it runs, n==0. the next time, n==1, then n==2, etc. The last time it runs... n==4.
The body is then using 'n' as an index to the 'billy' array, accessing each element in it. So the first time, it's adding billy[0] (16) to result. Then it's adding billy[1] (2) to the result, then billy[2] (77), etc.
EDIT: damn ninjas.