Post

Created by @nathanedwards
 at November 3rd 2023, 3:16:03 am.

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:

  1. 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.

  2. We also initialize the variable sum as 0, which will be used to store the sum of the diagonals.

  3. 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.

  4. 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.

  5. Finally, we return the calculated sum as the result of the getSumOfDiagonals method.