- A collection of variables having the same data type
- The variables are thought as being structured in two dimensions
- Each variable is accessed using:
(i) a name which is the same for all of them
(ii) a pair of indices that represent the position of the variable in each dimension
- In other words, a two-dimensional array is an array of arrays !!
- Specify the type of the variables followed by the size in each dimension
DataType ArrayName [ConstIntExpression][ConstIntExpression]
|
ArrayName [IndexExpression][IndexExpression]
|
- The IndexExpression may be just a constant, or a variable or even an expression
- The result of IndexExpression must be an integer value
- Examples: value[4][1], value[2*a+1][a-1] (assuming a is an integer)
- Assign a value: value[2][3]=100;
- Read a value into it: cin >> value[2][3];
- Write its contents: cout << value[2][3];
- Pass it as a parameter: y=sqrt[value[2][3]);
- Two-dimensional arrays can be initialized in a declaration
int value[2][3] = { {10, 20, 12} {13, 33, 45} };
- Two-dimensional arrays can also be initialized using two loop statements:
- No aggregate operations (assignment, comparison, arithmetic, etc.)
- Passing a two-dimensional array to a function ? Yes !!
- Sum the rows
- Sum the columns
- Sum all the elements
- Print the table
- Compute the average temperature per week
for(i=0; i<52; i++) { sum = 0.0; for(j=0; j<7; j++) sum = sum + temperature[i][j]; average = sum / 7; cout << "The average temperature of the " << i << "-th week is " << average << endl; }
- Compute the average temperature for each day of the week
for(j=0; j<7; j++) { sum = 0.0; for(i=0; i<52; i++) sum = sum + temperature[i][j]; average = sum / 52; cout << "The average temperature of the " << j << "-th day is " << average << endl; }
- Compute the average temperature of the year
sum = 0.0; for(i=0; i<52; i++) for(j=0; j<7; j++) sum = sum + temperature[i][j]; average = sum / (7*52); cout << "The average temperature of the year is " << average << endl; }
- Week by week
for(i=0; i<52; i++) { for(j=0; j<7; j++) cout << temperature[i][j] << " "; cout << endl; }
for(j=0; j<7; j++) { for(i=0; i<52; i++) cout << temperature[i][j] << " "; cout << endl; }