|
|
|
|
|
|
|
Initializing Multidimensional Arrays |
|
|
|
|
|
|
|
|
You can initialize multidimensional arrays. You assign the list of values to array elements in order, with the last array subscript changing and each of the former ones holding steady. Therefore, if you have an array |
|
|
|
|
|
|
|
|
the first three elements go into the Array[0], the next three into theArray[1], and so forth. |
|
|
|
|
|
|
|
|
You initialize this array by writing |
|
|
|
|
|
|
|
|
int theArray[5][3] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 } |
|
|
|
|
|
|
|
|
For the sake of clarity, you could group the initializations with braces. For example: |
|
|
|
|
|
|
|
|
int theArray[5][3] = { {1,2,3},
{4,5,6},
{7,8,9},
{10,11,12},
{13,14,15} }; |
|
|
|
|
|
|
|
|
The compiler ignores the inner braces, which just make it easier for the programmer to understand how the numbers are distributed. |
|
|
|
|
|
|
|
|
Each value must be separated by a comma, without regard to the braces. The entire initialization set must be within braces, and it must end with a semicolon. |
|
|
|
|
|
|
|
|
Listing 15.3 creates a two-dimensional array. The first dimension is the set of numbers from 0 to 5. The second dimension consists of the double of each value in the first dimension. |
|
|
|
|
|
|
|
|
LISTING 15.3 CREATING A MULTIDIMENSIONAL ARRAY |
|
|
|
 |
|
|
|
|
1: #include <iostream.h>
2: int main()
3: {
4: int SomeArray[5][2] = { {0,0}, {1,2}, {2,4}, {3,6}, {4,8}};
5: for (int i = 0; i<5; i++)
6: for (int j=0; j<2; j++)
7: {
8: cout << SomeArray[ << ][ << j << ]: ;
9: cout << SomeArray[i][j]<< endl;
10: }
11:
12: return 0;
13: } |
|
|
|
|
|