-2

I'm new to java. How can I find the sum of diagonals (that looks like /) in a 2D Matrix?

Let's say the matrix looks something like this:

4 6 7
2 4 7 
5 2 7

The sum of the diagonal(that looks like \) is 15 (4+4+7). Here's my code for that diagonal:

public static int Diagonal(int m[][]) { 
    int sum = 0;
    for(int row = 0; row < m[0].length; row++) {
        sum += m[row][row];
    }
    return sum; 
}   

How can I find the sum of the other diagonal that looks like (/)?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Find the relation between the row and col coordinate for that diagonal. (0,2),(1,1),(2,0) and apply it to a for loop – Tyler Dec 09 '19 at 18:03

2 Answers2

2

you can use this code

public static int Diagonal2(int m[][]) {   
    int sum=0;
    for(int row = 0; row < m[0].length; row++) {
        sum += m[row][m.length - row - 1];
    }
    return sum; 
}
b.GHILAS
  • 2,273
  • 1
  • 8
  • 16
0

Do it like

public class Main {
    public static void main(String[] args) {
        int[][] matrix = { { 4, 6, 7 }, { 2, 4, 7 }, { 5, 2, 7 } };
        StringBuilder sb = new StringBuilder();
        int sum = sumDiagonal(matrix, sb);
        sb.deleteCharAt(sb.length() - 1);
        System.out.println("The sum of the diagonal is " + sum + " (" + sb + ")");
    }

    public static int sumDiagonal(int m[][], StringBuilder sb) {
        int sum = 0;
        for (int row = 0; row < m[0].length; row++) {
            sum += m[row][m[0].length - row - 1];
            sb.append(m[row][m[0].length - row - 1] + "+");
        }
        return sum;
    }
}

Output

The sum of the diagonal is 16 (7+4+5)