简体   繁体   中英

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

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

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];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM