Java Program to Find Sum of Diagonal Elements
for (int i = 0; i < n; i++) sum += matrix[i][i];.Examples
How to Think About It
Algorithm
Code
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); } }
Dry Run
Let's trace the example matrix [[5,1,3],[2,7,4],[6,8,9]] through the code
Initialize sum
sum = 0
First iteration (i=0)
sum = 0 + matrix[0][0] = 0 + 5 = 5
Second iteration (i=1)
sum = 5 + matrix[1][1] = 5 + 7 = 12
Third iteration (i=2)
sum = 12 + matrix[2][2] = 12 + 9 = 21
End loop
Final sum = 21
| Iteration (i) | matrix[i][i] | Sum after addition |
|---|---|---|
| 0 | 5 | 5 |
| 1 | 7 | 12 |
| 2 | 9 | 21 |
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
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); } }
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); } }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop | O(n) | O(1) | Beginners and performance |
| Separate loops for both diagonals | O(n) | O(1) | When both diagonals are needed |
| Java streams | O(n) | O(1) | Modern Java style and concise code |
matrix[i][i] to access them.