Q 2. A 2 dimensional array of doubles has the same number of rows and columns (a square array). Assume the values
are already loaded in the array. Write a loop to calculate the sum total of the elements of the diagonal (the elements
with the same row and column subscript values). In the following example 4x4 2-d array, the elements on the diagonal
are in boldface type. Use the partial declarations given.
12 8 -11 7
6 3 0 2.9
7 7 -11 10
-3 -7 4 8
array< array, 4> mat = { the initial values would go here };
double sum = 0.0;
// write the code
Page 2 of 2 2013-12-09
for (int i(0); i < 4; i++)
sum += mat[i][i];
Q 3. A 2 dimensional array of doubles has the same number of rows and columns (a square array). Assume the values
are already loaded in the array. Write a loop to calculate the sum total of the elements of the anti-diagonal (the
elements whose row and column subscripts add up to the number of rows (or number of columns as they are equal) ?
1). In the following example 4x4 2-d array, the elements on the anti-diagonal are in boldface type. Use the partial
declarations given.
12 8 -11 7
6 3 0 2.9
7 7 -11 10
-3 -7 4 8
array< array, 4> mat = { the initial values would go here};
double sum = 0.0;
// write the code
Q 4. Repeat these questions by writing functions that receive the arrays as constant reference parameters and return
the appropriate values through the function name (via return statement). The function header could look like:
double sumDiag(const array< array, 4> & mat) {
// write the code
} // end function
double sumAntiDiag(const array< array, 4> & mat) {
double sum = 0.0;
for (int i(0); i < 4; i++)
sum += mat[i][3 - i]; // Note: i + (3 - i) = 4 - 1
return sum;
} // end function