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
Main diagonal elements are A[i][i]. - Loop iterates through indices 0 to 2. - Each diagonal element added to sum. - Together demonstrates diagonal sum calculation. Conclusion: Demonstrates calculation of main diagonal sum in a matrix.