Sum of Secondary Diagonal Elements

This program calculates the sum of secondary diagonal elements of a matrix.

Problem Statement

Write a Java program to calculate the sum of secondary diagonal elements of a 3x3 matrix.

Source Code

1 public class MatrixSecondaryDiagonalSum {
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][3-1-i];
7 }
8 System.out.println("Sum of secondary diagonal: "+sum);
9 }
10 }

Program Output

Sum of secondary diagonal: 15

Explanation

The secondary diagonal elements are accessed as A[i][n-1-i], and a loop accumulates each of these into sum, demonstrating how multidimensional arrays can access diagonals differently from the main diagonal.

Quick Links to Explore