< previous page page_232 next page >

Page 232
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
int theArray[5][3]
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

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 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:    }

 
< previous page page_232 next page >

If you like this book, buy it!