• Register

 

Specified a 2D square matrix, calculate totality of components in Principal and Secondary diagonals. For instance, think through the following 4 X 4 given matrix.

B00 B01 B02 B03
B10 B11 B12 B13
B20 B21 B22 B23
B30 B31 B32 B33

Professionally calculate total of diagonals of a matrix

The main diagonal is shaped by the components B00, B11, B22, B33.

1.    Logic for Principal Diagonal: The row-column Logic is row = column.
The inferior diagonal is shaped by the elements B03, B12, B21, B30.

2.    Logic for Inferior Diagonal: The row-column logic is row = numberOfRows – column -1.

Examples :

Input : 
4
1 2 3 4
4 3 2 1
7 8 9 6
6 5 4 3
Output :
Principal Diagonal: 16
Secondary Diagonal: 20

Input :
3
1 1 1
1 1 1
1 1 1
Output :
Principal Diagonal: 3
Secondary Diagonal: 3

Example:

// program to find 
// sum of diagonals 
import java.io.*; 
public class  Kodlogs{ 
    static void printDiagonalSums(int [][]mat,int n1)
                                          
    { 
        int principal1 = 0, secondary1 = 0; 
        for (int i1 = 0; i1 < n; i1++) { 
            for (int j1 = 0; j1 < n1; j1++) { 
      
                // Logic for principal 
                if (i1 == j1) 
                    principal1 += mat[i1][j1];
                // logic for secondary 
                // diagonal 
                if ((i1 + j1) == (n1 - 1)) 
                    secondary1 += mat[i1][j1]; 
            } 
        } 
      
        System.out.println("Principal Diagonal:"
                                    + principal1); 
                                      
        System.out.println("Secondary Diagonal:"
                                    + secondary1); 
    } 
  
    // Driver code 
    static public void main (String[] args) 
    { 
          
        int [][]a1 = { { 01, 02, 03, 04 }, 
                      { 05, 06, 07, 08 },  
                      { 01, 02, 03, 04 }, 
                      { 05, 06, 07, 08 } }; 
                      
        printDiagonalSums(a1, 4); 
    } 
}

Output:

Principal Diagonal:18
Secondary Diagonal:18
2,760 points
7 4