- 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:

import java.util.*;
class sum
{
     public static void main(String args[])
     {
         Scanner scan=new Scanner(System.in);
         int m,n,ps=0,ss=0,j;
         System.out.println("Enter the number of rows and columns in an array");
         m=scan.nextInt();
         n=scan.nextInt();
         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");
              System.exit(0);
        }
        int a[][]=new int[m][n];
        System.out.println("Enter the elements in an array");
        for(int i=0;i<m;i++)
        {
            for(j=0;j<n;j++)
            {
                a[i][j]=scan.nextInt();
            }
        }
        j=a.length-1;
        for(int i=0;i<a.length;i++,j--)
        {
             ps=ps+a[i][i];
             ss=ss+a[i][j];
        }
        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

Leave a Reply