Understanding Arrays

Hey,
I am currently studying arrays and understand the basic principle of accessing and initialising them but I am stuck on the example code given.
I am trying to understand the logic behind the source code in the given example. Once compiled the answer displayed on cout is 12206.

// arrays example
#include <iostream>
using namespace std;

int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;

int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}


Cheers and thanks for the help in advanced
There's nothing special in the code above
int billy [] = {16, 2, 77, 40, 12071}; declares an array of 5 elements and initializes them with the values given
1
2
3
4
for ( n=0 ; n<5 ; n++ )
{
    result += billy[n];
}
sums up the values stored in the array
16+2+77+40+12071 = 12206
ugh @ examples using global variables. It's like they're trying to teach people the wrong way to do things.


Anyway...

The for loop (for ( n=0 ; n<5 ; n++ )) is performed 5 times. Each time, the variable 'n' will be increased by 1. So the first time it runs, n=0, then the next time n=1, then n=2, etc

This: result += billy[n]; uses 'n' as the "index" of the array. The index says which element in the array we want to take.

For example... billy[0] gives us the first element in the array (16)
billy[1] gives us the 2nd (2)
billy[2] gives us 77
etc


Since our index is 'n', and 'n' is increasing every time the loop runs, this means that we're getting a different element from the billy array every time it runs.

Effectively... this:
1
2
3
4
for ( n=0 ; n<5 ; n++ )
{
  result += billy[n];
}

is a shorter way or writing this:
1
2
3
4
5
result += billy[0];
result += billy[1];
result += billy[2];
result += billy[3];
result += billy[4];


The end result is that our 'result' variable sums every element in the 'billy' array.


EDIT: doh too slow. XD
Last edited on
Thank you both I was just curious for what the For statement was used for. Cheers you both have helped me to understand :)
Topic archived. No new replies allowed.