Eg: If A is the matrix of order 3×3
1 2 3
A= 4 5 6
7 8 9
Principal diagonal elements are: 1,5,9
Principal sum 1+5+9=15
Secondary diagonal elements are: 3,5,7
Secondary sum 3+5+7=15
The logic to find principal diagonal elements are very simple that is if row value is equal to column then the elements are principal diagonal elements and hence we can easily find the sum of these elements. In the same way, the logic to find secondary diagonal elements is to check whether the sum of row and column index is equal to the dimension of a matrix.
I know this is a very tedious way to find the principal and secondary so I have an easy way to find the sums. Here is the algorithm:
2)input the dimensions of the matrix.
3)Check whether the matrix is a square matrix or nothing
4)Store all the values of the matrix which is having same indexes and find sum this is the principal sum
5)Store all the values of the matrix in which one index is increasing and another index is decreasing so that we find the secondary diagonal elements
6)Repeat step 4 and 5 till we finish the elements of the matrix.
Code goes here:
public static void main(String args)
Scanner scan=new Scanner(System.in);
System.out.println("Enter the number of rows and columns in an array");
if(m!=n) //To check whether the entered matrix is square matrix or not
System.out.println("The matrix is not a square matrix hence we cannot
calculate the principle and secondary sum");
int a=new int[m][n];
System.out.println("Enter the elements in an array");
System.out.println("principle sum ="+ps);
System.out.println("Secondary sum ="+ss);
Feel free to drop your queries and suggestions.
Happy coding 😉
Go through our other java posts click here