An array is like a drawer shelves. Have you seen such a shelves lately?
Here we have a shelves with 6 drawers. In C++, you would 'build' the shelves as follows:
Drawer shelves[6];
And to access any particular drawer, you have to indicate its index - which is just the red number next to the drawers in the above picture. So for example, let's say you would like to print out the content of drawer number 3, you would do something like as follows:
cout << shelves[3];
If you want to print the content of every drawer, you can use a loop, such as a follows:
for (int i=0; i<10; i++)
cout << shelves[i] << endl;
Arrays can be multidimensional. It can be 2-dimensional, for example, as is the case for the drawer shelves below:
To build the shelves above in C++, you can do as follows:
Drawer shelve2d[4][3];
where 4 is the number of rows, and 3 the number of columns. Note the ordering - we order by row first.
Now to access any particular drawer, we use double index. For example, to print the content of the drawer at row 2, column 1, we do as follows:
cout << shelve2d[2][1];
And to print the content for all of the drawers, we can use a nested loop:
for (int j=0; j<4; j++)
for (int i=0; i<3; i++)
cout << shelve2d[j][i] << endl;
No comments:
Post a Comment