Question:
Consider a two-dimensional array matrix
of integers with dimensions m
by n
. Write a Java method getSumOfDiagonals
that takes in the array matrix
, and returns the sum of all values in both the main diagonal and the anti-diagonal of the matrix.
The main diagonal includes the elements where the row index is equal to the column index, and the anti-diagonal includes the elements where the row index plus the column index equals n - 1
.
You may assume that matrix
is a square matrix, meaning m = n
.
Your implementation should have the following signature:
public static int getSumOfDiagonals(int[][] matrix) {
}
Write the implementation for the getSumOfDiagonals
method and provide a step-by-step detailed explanation.
Answer:
public static int getSumOfDiagonals(int[][] matrix) {
int n = matrix.length;
int sum = 0;
// Calculating the sum of the main diagonal
for (int i = 0; i < n; i++) {
sum += matrix[i][i];
}
// Calculating the sum of the anti-diagonal
for (int i = 0; i < n; i++) {
sum += matrix[i][n - 1 - i];
}
return sum;
}
Explanation:
We start by initializing the variable n
as the length of the matrix. Since the matrix is square, the number of rows is equal to the number of columns.
We also initialize the variable sum
as 0, which will be used to store the sum of the diagonals.
We now calculate the sum of the main diagonal. The main diagonal consists of elements where the row index is equal to the column index. We use a for loop from i = 0
to i < n
, and add matrix[i][i]
to the sum
variable.
Next, we calculate the sum of the anti-diagonal. The anti-diagonal consists of elements where the row index plus the column index equals n - 1
. We use a for loop from i = 0
to i < n
, and add matrix[i][n - 1 - i]
to the sum
variable.
Finally, we return the calculated sum
as the result of the getSumOfDiagonals
method.