# Sum of secondary diagonal of a matrix in Java

In the last tutorial, we learned about the sum of the principal diagonal of a matrix, in this tutorial we will see how to find the sum of the secondary diagonal of a matrix in Java.

Have a look at the below matrix:

A1 A2 A3

B1 B2 B3

C1 C2 C3

Here the principal diagonal is A3 – B2- C1, and our task is to find the sum of these elements.

It has to be noted that the matrix can be of any dimension, though it needs to be a square matrix.

## Java program to find the sum of secondary diagonal of a matrix in Java

Here is how the code will look:

import java.util.*; public class test { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int arr[][]=new int[3][3]; int dsum=0; System.out.println("Enter elements in matrix"); for(int i=0;i<=2;i++) { for(int j=0;j<=2;j++) { arr[i][j]=sc.nextInt(); if(i+j==2) { dsum=dsum+arr[i][j]; } } } System.out.println("The sum of secondary principal diagonal is "+dsum); } }

This will generate the following output:

Enter elements in matrix 1 2 3 4 5 6 7 8 9 The sum of secondary principal diagonal is 15

Hope this helped you out.

Also read:

it works only for 3×3 matrix because the condition says i+j==2 this statement for only 3×3