Sum of Main Diagonal Elements
This program calculates the sum of main diagonal elements of a matrix.
Problem Statement
Write a Java program to calculate the sum of main diagonal elements of a 3x3 matrix.
Source Code
| 1 | public class MatrixDiagonalSum { |
| 2 | public static void main(String[] args) { |
| 3 | int[][] A = {{1,2,3},{4,5,6},{7,8,9}}; |
| 4 | int sum=0; |
| 5 | for(int i=0;i<3;i++){ |
| 6 | sum+=A[i][i]; |
| 7 | } |
| 8 | System.out.println("Sum of main diagonal: "+sum); |
| 9 | } |
| 10 | } |
Program Output
Sum of main diagonal: 15
Explanation
The main diagonal elements are accessed as A[i][i], and a loop from 0 to 2 accumulates each diagonal element into sum, demonstrating a straightforward diagonal sum calculation on a matrix.