Sum of principal diagonal of a Matrix in Java

Hello coders, today we will see how to find the sum of principal diagonal in a matrix in Java.

A matrix is nothing but a 2D array, and since we need to work with diagonal therefore we need a square matrix, that is, the same number of rows and columns.

Have a look at the below matrix:

A1     A2     A3

B1     B2     B3

C1     C2     C3

Here the principal diagonal is A1 – B2- C3, 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 Sum of the principal diagonal of a Matrix

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)
    		   {
    			   dsum=dsum+arr[i][j];
    		   }
    	   }
    	   
       }
       System.out.println("The sum of principal diagonal is "+dsum);
       
       
       
  }
}
       

The above code will generate the following result:

Enter elements in matrix

13
14
15
32
97
16
23
21
45
The sum of principal diagonal is 155

Hope this helped you out.

Have a nice day ahead.

Also, read:

How To Check The Internet Connection In Java?

Find the next greater number from the same set of digits in C++

How to find the difference or gap of days between two dates in python

Leave a Reply

Your email address will not be published. Required fields are marked *