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 diagnol elements and secondary diagonal elements.Principal diagonal elements are those which start at top leftmost elemnt of matrix and end at bottom rightmost element of a matrix.Secondary diagonal elements are vicevera.
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 elemnts 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 matrix.
3)Check whether the matrix is square matrix or nothing
4)Store all the values of matrix which is having same indexes and find sum this is principal sum
5)Store all the values of 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 elemnts of matrix.
7)Stop

Code goes here:

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Advertisment ad adsense adlogger