Java – How do I find the sum of diagonal elements in 2d ArrayList?

How do I find the sum of diagonal elements in 2d ArrayList?… here is a solution to the problem.

How do I find the sum of diagonal elements in 2d ArrayList?

I need to find the sum of diagonals in 2D ArrayList

List<List<Integer>> arr

Solution

public static int diagonalDifference(List<List<Integer>> arr) {

int size = arr.size();
        int add1=0;
        int add2=0;
        for(int i=0 ; i < size ; i++){
           add1 = add1+  arr.get(i).get(i);
           add2 = add2+ arr.get(i).get(size -i-1);

}

int absoluteValue =Math.abs( add1 - add2);

return absoluteValue;

}

Related Problems and Solutions