how to calculate the sum of elements after the diagonal in 2D array in java?

那年仲夏 提交于 2021-01-29 08:26:24

问题


I have a function that I need to calculate the sum of elements after the diagonal in the 2D array, but the problem is that the function return the sum of the elements in the diagonal.

What I need is that if I have a matrix like this:

1 2 3
4 5 6
7 8 9

The elements of the diagonal are = 1 5 9

What I need is to calculate the numbers that follow after these diagonal numbers, so it will be like this:

1 2 3
4 5 6
7 8 9

sum = 2+3+6 = 11

I would appreciate it if someone could help me to fix my problem.

this my code:

public int calculate(){

        int sum = 0;

        for(int row = 0; row <matrix.length; row++){
            for(int col = 0; col < matrix[row].length; col++){
                if(row == col){
                 sum = sum + row+1 ;
                }
            }
        }
        System.out.println("the sum is: " + sum );
        return sum;
    }

public static void main(String[] args) {

    int[][] ma = new int[2][2];
    Question2 q2 = new Question2(2, 2, ma);
    q2.fill();
    q2.calculate();
}

the output is:

2 1 
2 1 
the sum is: 3

回答1:


You want col to go through all elements, being always bigger than the diagonal.

Therefore try:

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


来源:https://stackoverflow.com/questions/27656935/how-to-calculate-the-sum-of-elements-after-the-diagonal-in-2d-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!