Java

Java program to find the sum of principal and secondary diagonal elements.

In this article let’s learn how to find the sum of principle diagonal elements and secondary diagonal elements. Principal diagonal elements are those which start at the top leftmost element of matrix and end at the bottom rightmost element of a matrix. Secondary diagonal elements are vice-versa.
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:

Algorithm:

1)Start
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.
7)Stop

Code goes here:

Feel free to drop your queries and suggestions.

Happy coding 😉

Go through our other java posts click here