Open In App

Java Program to Compute the Sum of Diagonals of a Matrix

Last Updated : 21 May, 2025
Suggest changes
Share
Like Article
Like
Report

For a given 2D square matrix of size N*N, our task is to find the sum of elements in the Principal and Secondary diagonals.

For example, analyze the following 4 × 4 input matrix.

m00 m01 m02 m03
m10 m11 m12 m13
m20 m21 m22 m23
m30 m31 m32 m33

Basic Input/Output:

Input 1:   6 7 3 4
               8 9 2 1
              1 2 9 6
              6 5 7 2


Output 1: Principal Diagonal: 26
                 Secondary Diagonal: 14
 

Input 2: 2 2 2
              1 1 1
             3 3 3


Output 2:  Principal Diagonal: 6
                  Secondary Diagonal: 6

Understanding Diagonals in a Square Matrix:

  • The diagonal on which the row number and column number are the same (like elements in positions like (1,1), (2,2), (3,3), (4,4), and so on) is known as the principal diagonal or main diagonal of a square matrix.
  • The diagonal in which the sum of the row number and column number is equal to one less than the size of the matrix is called the secondary diagonal. It runs from the top-right corner to the bottom-left corner of a square matrix.


Naive Approach: Using Nested Loops to Identify Diagonals

We are going to use nested loops to iterate over the elements in the matrix and going to check if it belongs to the principal or secondary diagonal based on the condition.

Example: Below is the naive approach for finding the sum of diagonals of a matrix.

Java
// Java Program to Find the Sum of Diagonals of a Matrix // Importing input output classes import java.io.*; // Main Class public class Geeks {    // To calculate Sum of Diagonals   static void Sum_of_Diagonals1(int[][] matrix, int N)   {   // Declaring and initializing two variables to zero   // initially for primary and secondary diagonal   // count   int Pd = 0, Sd = 0;     // Two Nested for loops for iteration over a matrix   // Outer loop for rows   for (int k = 0; k < N; k++) {     // Inner loop for columns   for (int l = 0; l < N; l++) {     // Condition for the principal   // diagonal   if (k == l)   Pd += matrix[k][l];     // Condition for the secondary diagonal   if ((k + l) == (N - 1))   Sd += matrix[k][l];   }   }     // Print and display the sum of primary diagonal   System.out.println("Sum of Principal Diagonal:"  + Pd);   // Print and display the sum of secondary diagonal   System.out.println("Sum of Secondary Diagonal:"  + Sd);   }     // Main driver method  static public void main(String[] args)  {  // Input integer array  // Custom entries in an array  int[][] b = { { 8, 2, 13, 4 },  { 9, 16, 17, 8 },  { 1, 22, 3, 14 },  { 15, 6, 17, 8 } };  // Passing the array as an argument to the  // function defined above  Sum_of_Diagonals1(b, 4);    } } 

Output
Sum of Principal Diagonal:35 Sum of Secondary Diagonal:58 

Time complexity: O(N2)
Auxiliary space: O(1)

Let's now discuss the efficient approach in order to solve this problem.

Optimized Approach: Access Diagonal Elements Directly by Index

The idea to find the sum of values of principal diagonal is to iterate to N and use the value of matrix[row][row] for the summation of principal diagonal and to find the sum of values of secondary diagonal is to use the value of matrix[row][N - (row + 1)] for summation.

Example: Below is the efficient approach for finding the sum of diagonals of a matrix.

Java
// Java Program to Find the Sum of Diagonals of a Matrix // Importing input output classes import java.io.*; // Main Class public class Geeks {    // To calculate Sum of Diagonals  static void Sum_of_Diagonals(int[][] matrix, int N)  {  // Declaring and initializing two variables to zero  // initially for primary and secondary diagonal  // count  int Pd = 0, Sd = 0;  for(int i=0; i<N; i++)  {  // Since for primary diagonal sum the value of  // row and column are equal   Pd += matrix[i][i];    // For secondary diagonal sum values of i'th index  // and j'th index sum is equal to n-1 at each   // stage of matrix  Sd += matrix[i][N-(i+1)];  }      // Print and display the sum of primary diagonal  System.out.println("Sum of Principal Diagonal:"  + Pd);  // Print and display the sum of secondary diagonal  System.out.println("Sum of Secondary Diagonal:"  + Sd);  }    // Main driver method  static public void main(String[] args)  {  // Input integer array  // Custom entries in an array  int[][] b = { { 8, 2, 13, 4 },  { 9, 16, 17, 8 },  { 1, 22, 3, 14 },  { 15, 6, 17, 8 } };  // Passing the array as an argument to the  // function defined above  Sum_of_Diagonals(b, 4);  } } 

Output
Sum of Principal Diagonal:35 Sum of Secondary Diagonal:58 

Time complexity: O(N)
Auxiliary space: O(1)


Next Article

Similar Reads

Article Tags :
Practice Tags :