|
|
|
|
|
|
|
we can use the following declaration. |
|
|
|
|
|
|
|
|
int table[2][3] =
{
{14, 3, -5},
{0, 46, 7}
}; |
|
|
|
|
|
|
|
|
In this declaration, the initializer list consists of two items, each of which is itself an initializer list. The first inner initializer list stores 14, 3, and -5 into row 0 of the table; the second stores 0, 46, and 7 into row 1. The use of two initializer lists makes sense if you think of each row of the table as a onedimensional array of three ints. The first initializer list initializes the first array (the first row), and the second list initializes the second array (the second row). Later in the chapter, we revisit this notion of viewing a twodimensional array as an array of arrays. |
|
|
|
|
|
|
|
|
Initializing a table in its declaration is impractical if the table is large. For a 100-row by 100-column table, you don't want to list 10,000 values. If the values are all different, you should store them into a file and input them into the table at run time. If the values are all the same, the usual approach is to use nested For loops and an assignment statement. Here is a generalpurpose code segment that zeroes out a table with NUM_ROWS rows and NUM_COLS columns: |
|
|
|
|
|
|
|
|
for (row = 0; row < NUM_ROWS; row++)
// Invariant (prior to test):
// table[0..row-1][0..NUM_COLS-1] == 0
// && 0 <= row <= NUM_ROWS
for (col = 0; col < NUM_COLS; col++)
// Invariant (prior to test):
// table[row][0..col1] == 0
// && 0 <= col <= NUM_COLS
table[row][col] = 0; |
|
|
|
|
|
|
|
|
In this case, we initialized the table a row at a time, but we could just as easily have run through each column instead. The order doesn't matter as long as we access every element. |
|
|
|
|
|
|
|
|
If we wish to print out a table with one row per line, then we have another case of row processing: |
|
|
|
|
|