How to find the sum of boundary elements of a matrix in Java

1 Answer

0 votes
public class MyClass {
    private static int getBoundarySum(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int sum = 0;
          
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (i == 0 || j == 0 || i == rows - 1  || j == cols - 1)
                    sum += matrix[i][j];
            }
        }
          
        return sum;
    }
      
    public static void main(String args[]) {
        int matrix[][] = {{1,  2,  3,  4},
                          {5,  6,  7,  8},
                          {9, 10, 11, 12}};
  
        // 1 + 2 + 3 + 4 + 8 + 12 + 11 + 10 + 9 + 5 + 65
          
        System.out.println(getBoundarySum(matrix));
    }
}
  
  
  
  
/*
run:
  
65
  
*/

 



answered Jun 17, 2023 by avibootz
edited Jun 30, 2023 by avibootz

Related questions

1 answer 138 views
1 answer 172 views
1 answer 116 views
1 answer 95 views
1 answer 96 views
...