Search code examples
javamatrixmultidimensional-arraysumdiagonal

How to find sum of elements above secondary diagonal in matrix?


I tried searching for the solution to this problem for a while now and couldn't find anything. How do I sum the elements above the secondary diagonal in a matrix (just with loops, nothing fancy) in Java?

This is what I tried:

public static void Page106Ex3$H(int[][] mat) {
    int sum = 0;

    for (int i = 1; i < mat.length; i++) {
        for (int j = i-1; j >= 0; j--) {
            sum += mat[i][j];
        }
    }

    System.out.println("Sum: " + sum);
}

Solution

  • If the elements on the secondary are not included, the number of columns in the nested loop should be decremented with indexes starting from 0.

    public static int sumOver2ndDiagonal(int[][] arr) {
        int sum = 0;
        for (int i = 0, n = arr.length - 1; i < n; i++) {
            for (int j = 0, m = arr[i].length - 1 - i; j < m; j++) {
                sum += arr[i][j];
            }
        }
        return sum;
    }
    

    Test:

    System.out.println(sumOver2ndDiagonal(
        new int[][]{
            { 1,  2,  3,  4},
            { 5,  6,  7,  8},
            { 9, 10, 11, 12},
            {13, 14, 15, 16}
        }
    ));
    // 1 + 2 + 3 + 5 + 6 + 9
    // -> 26