Arrays and Loops
Arrays can be conveniently initialized by using a loop. The statement:
for(int i = 0; i < 10; i++)
arrayOfInt[i] = i;
initializes each of the ten array elements to the corresponding index.
For bi-dimensional arrays two nested loops can be used. The following
statement
initializes each element to the product of row and column index:
for(int i = 0; i < 3; i++)
for(int j = 0; j < 5; j++)
BiDimensionalArrayOfInt[i][j] = i * j;
Arrays can have any dimension, although using more than three dimensions
is strongly advised against in order to avoid the confusion arising
by the impossibility to visualize a space in four or more dimensions.
A three dimension-array can be initialized by means of three nested loops.
for(int i = 0; i < 2; i++)
for(int j = 0; j < 3; j++)
for(int k = 0; k < 4; k++)
TriDimensionalArrayOfInt[i][j][k] = i * j * k;
The number of dimensions is also known as the "level" of the array. Arrays
are visited – in order
to print out their contents, for example – in a similar way.
Example
#include <iostream>
using namespace std;
int main()
{
int arrayOfInt[10];
int BiDimensionalArrayOfInt[3][5];
int TriDimensionalArrayOfInt[2][3][4];
for(int i = 0; i < 10; i++)
arrayOfInt[i] = i;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 5; j++)
BiDimensionalArrayOfInt[i][j] = i * j;
for(int i = 0; i < 2; i++)
for(int j = 0; j < 3; j++)
for(int k = 0; k < 4; k++)
TriDimensionalArrayOfInt[i][j][k] = i * j * k;
cout << "one-dimension array:\n\n";
for(int i = 0; i < 10; i++)
cout << arrayOfInt[i] << endl;
cout << "\n\n";
cout << "two-dimension array:\n\n";
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 5; j++)
{
cout << BiDimensionalArrayOfInt[i][j] << " ";
}
cout << endl;
}
cout << "\n\n";
cout << "three-dimension array:\n\n";
for(int i = 0; i < 2; i++)
for(int j = 0; j < 3; j++)
for(int k = 0; k < 4; k++)
cout << "level " << i << " row " << j << " column " << k << ", content:" << TriDimensionalArrayOfInt[i][j][k] << endl;
}
Output
one-dimension array:
0
1
2
3
4
5
6
7
8
9
two-dimension array:
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
three-dimension array:
level 0 row 0 column 0, content:0
level 0 row 0 column 1, content:0
level 0 row 0 column 2, content:0
level 0 row 0 column 3, content:0
level 0 row 1 column 0, content:0
level 0 row 1 column 1, content:0
level 0 row 1 column 2, content:0
level 0 row 1 column 3, content:0
level 0 row 2 column 0, content:0
level 0 row 2 column 1, content:0
level 0 row 2 column 2, content:0
level 0 row 2 column 3, content:0
level 1 row 0 column 0, content:0
level 1 row 0 column 1, content:0
level 1 row 0 column 2, content:0
level 1 row 0 column 3, content:0
level 1 row 1 column 0, content:0
level 1 row 1 column 1, content:1
level 1 row 1 column 2, content:2
level 1 row 1 column 3, content:3
level 1 row 2 column 0, content:0
level 1 row 2 column 1, content:2
level 1 row 2 column 2, content:4
level 1 row 2 column 3, content:6