Hey this is my first post. Im trying to teach myself c++ and have reached the Arrays section in the documentation of this site.
However, I cant figure out how the example of the 2 dimensional array works. I can see how the table works mathmatically but I cant see the process of filling each slot in the array. Surely as 'n' increases so does 'm' and therefore only [0][0],[1][1],[2][2],[3][3],[4][4] and [5][5] get filled? Im really rusty at maths etc so hopefully some of you could help clear this up for me? The code im refering to is below. And heres a link to the page: http://www.cplusplus.com/doc/tutorial/arrays/
I appreciate your help.
Cheers, Gareth.
#define WIDTH 5
#define HEIGHT 3
int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++)
{
jimmy[n][m]=(n+1)*(m+1);
}
return 0;
}
Here's a play-by-play of what happens in this program:
for a moment lets pretend we just have this:
1 2 3 4 5 6
int main() {
for ( n=0; n<HEIGHT; n++ ) {
jimmy[n] = n+1;
}
return 0;
}
As it loops, it will do
jimmy[0] = 1;
jimmy[1] = 2;
jimmy[2] = 3;
That's how it will iterate with a single dimentional loop. Now we can add in a nested loop:
1 2 3 4 5 6 7 8 9
int main() {
for ( n=0; n<HEIGHT; n++ ) {
for (m=0;m<WIDTH;m++)
jimmy[n][m]=(n+1)*(m+1);
}
return 0;
}
jimmy[0][0] = 1;
///n, AKA HEIGHT is still 0, because we're doing the nested loop still, not the first loop.
jimmy[0][1] = 2;
jimmy[0][2]
//etc
jimmy[1][0]
jimmy[1][1]
//etc, until
jimmy[3][5]
So you can see, the inner loop will run it's course entirely before the outer loop cycles again. That is why every dimension of your variable jimmy is being set.