Array Sum (Find sum of all diagonal elements and boundary elements)

5.2k views Asked by At

Given a 2-d square matrix of order ‘n’, find the sum of elements of both diagonals and all boundaries elements. Boundary elements refer to the elements present on all the four boundaries of matrix.

Can anyone code this in java ? Size of array will be always N*N .

enter image description here

Here given 5*5 array
8 18 18 1 10

12 3 13 6 19

17 11 18 10 19

10 13 12 11 14

3 1 19 11 1

output : 232

2

There are 2 answers

0
Chandan Nick On

I have solved this ,here is the solution

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int M = sc.nextInt();
    int[][] arr = new int[M][M];
    for (int row = 0; row < M; row++) {
        for (int col = 0; col < M; col++) {
            arr[row][col] = sc.nextInt();
        }
    }
    int boundrySum = 0, requiredSum = 0;
    for (int row = 0; row < M; row++) {
        for (int col = 0; col < M; col++) {
            if (row == 0 || col == 0 || row == M - 1 || col == M - 1) {
                boundrySum = boundrySum + arr[row][j];
            }
        }
    }
    int diagonal1Sum = 0, diagonal2Sum = 0;
    for (int row = 0; row < M; row++) {
        for (int col = 0; col < M; col++) {
            if (row == col)
                diagonal1Sum = diagonal1Sum + arr[row][col];

            else if ((row + col) == (M - 1))
                diagonal2Sum = diagonal2Sum + arr[row][col];
        }
    }
    requiredSum = boundrySum + diagonal1Sum + diagonal2Sum
            - (arr[0][0] + arr[0][M - 1] + arr[M - 1][0] + arr[M - 1][M - 1]);
    System.out.println(requiredSum);
}

}

2
Tavi On

In order to achieve what you want, you should know some interesting properties of matrix.

  1. The upper boundary known as 1st row can be used doing that:
for (int i = ; i < n; i ++ )
  sum += matrix[0][i]

This means you are traversing each element of the first row.

2.Then you should try to do the same with the first column of the matrix, and the code will look like this:

for (int i = ; i < n; i ++ )
  sum += matrix[i][0]

For the last row or column, you gotta replace the 0 with n-1 and you get the job done. Try to play a bit with these indexes and see what`s going on.

Useful links: https://www.go4expert.com/forums/border-elements-matrix-t33678/

The main diagonal have an interesting property, that i is equal with j. For example in a squared matrix, elements of the main diagonal are on position 0,0 - 1,1 - 2,2 and so on...

browse all rows
  browse all cells
    if i == j (is in main diagonal):
        increase one sum
    if i == n - j + 1 (the other diagonal)
        increase the second sum

The formula for the second diagonal is i should be equal to n-j+1.

See this question calculate the sum of diagonals in a matrix