0
0
JavaProgramBeginner · 2 min read

Java Program to Find Sum of Diagonal Elements

You can find the sum of diagonal elements in Java by looping through the matrix and adding elements where the row and column indexes are equal using for (int i = 0; i < n; i++) sum += matrix[i][i];.
📋

Examples

Input[[1,2],[3,4]]
Output5
Input[[5,1,3],[2,7,4],[6,8,9]]
Output21
Input[[10]]
Output10
🧠

How to Think About It

To find the sum of diagonal elements, think of a square matrix where the diagonal elements are those with the same row and column index. You just add these elements together by checking where the row number equals the column number.
📐

Algorithm

1
Get the size of the square matrix.
2
Initialize a variable sum to 0.
3
Loop through the matrix from 0 to size-1.
4
Add the element at position [i][i] to sum.
5
After the loop ends, return or print the sum.
💻

Code

java
public class DiagonalSum {
    public static void main(String[] args) {
        int[][] matrix = {{5, 1, 3}, {2, 7, 4}, {6, 8, 9}};
        int sum = 0;
        for (int i = 0; i < matrix.length; i++) {
            sum += matrix[i][i];
        }
        System.out.println("Sum of diagonal elements: " + sum);
    }
}
Output
Sum of diagonal elements: 21
🔍

Dry Run

Let's trace the example matrix [[5,1,3],[2,7,4],[6,8,9]] through the code

1

Initialize sum

sum = 0

2

First iteration (i=0)

sum = 0 + matrix[0][0] = 0 + 5 = 5

3

Second iteration (i=1)

sum = 5 + matrix[1][1] = 5 + 7 = 12

4

Third iteration (i=2)

sum = 12 + matrix[2][2] = 12 + 9 = 21

5

End loop

Final sum = 21

Iteration (i)matrix[i][i]Sum after addition
055
1712
2921
💡

Why This Works

Step 1: Identify diagonal elements

Diagonal elements have the same row and column index, so we use matrix[i][i] to access them.

Step 2: Sum elements in a loop

We loop through the matrix indices and add each diagonal element to the sum using sum += matrix[i][i].

Step 3: Output the result

After the loop, the sum contains the total of all diagonal elements, which we print.

🔄

Alternative Approaches

Using separate loops for primary and secondary diagonals
java
public class DiagonalSum {
    public static void main(String[] args) {
        int[][] matrix = {{5, 1, 3}, {2, 7, 4}, {6, 8, 9}};
        int sumPrimary = 0;
        int sumSecondary = 0;
        int n = matrix.length;
        for (int i = 0; i < n; i++) {
            sumPrimary += matrix[i][i];
            sumSecondary += matrix[i][n - 1 - i];
        }
        System.out.println("Sum of primary diagonal: " + sumPrimary);
        System.out.println("Sum of secondary diagonal: " + sumSecondary);
    }
}
This approach calculates both diagonals separately, useful if you want both sums, but slightly more code.
Using streams (Java 8+)
java
import java.util.stream.IntStream;
public class DiagonalSum {
    public static void main(String[] args) {
        int[][] matrix = {{5, 1, 3}, {2, 7, 4}, {6, 8, 9}};
        int sum = IntStream.range(0, matrix.length)
                           .map(i -> matrix[i][i])
                           .sum();
        System.out.println("Sum of diagonal elements: " + sum);
    }
}
This uses Java streams for a concise and modern approach but may be less clear for beginners.

Complexity: O(n) time, O(1) space

Time Complexity

The program loops once through the matrix diagonal elements, so it runs in linear time relative to the matrix size, O(n).

Space Complexity

Only a few variables are used for sum and loop counters, so space complexity is constant, O(1).

Which Approach is Fastest?

The simple loop approach is fastest and easiest to understand; stream-based methods add overhead but improve readability for some.

ApproachTimeSpaceBest For
Simple loopO(n)O(1)Beginners and performance
Separate loops for both diagonalsO(n)O(1)When both diagonals are needed
Java streamsO(n)O(1)Modern Java style and concise code
💡
Remember, diagonal elements have the same row and column index, so use matrix[i][i] to access them.
⚠️
A common mistake is trying to sum elements without checking that the matrix is square, which can cause errors.