# Calculate Primary and Secondary Diagonal

Write an algorithm that calculates all the elements of rows and columns of a square matrix and calculate the total of primary and secondary diagonal.

#### Asher The King Profile Answers by Asher The King

• Jul 10th, 2011

int sum=0;
For (int i=0;i<Line;i++)
For(int j=0;j<COL;j++)
{
//Primary diagonal
if(i==j )sum += A[i][j];
//Secondary diagonal
if(i==(COL-j))sum += A[i][j];
}

#### Ashima

• Aug 9th, 2012

Assuming the matrix size is row, col and i represents the row and j represents the col.
Get the primary Diagonal where i==j and secondary diagonal where i==j-1.
Below is the code for that.

```Codefor (int i = 0; i < row; i++)
{
int j = 0;
while (j < col)
{
//Primary diagonal
if (i == j) sum += A[i][j];
j++;
//Secondary diagonal
if (i == (col - j)) sum += A[i][j - 1];
}
}```

#### JosephVP

• Jul 24th, 2014

As it is a Square Matrix, we can do with single Loop, Please follow the below algorithm.

```Codeprivate static void findSumOfPrimaryAndSecondaryDiagonal(int[][] sortedMatrix, int rowStartPos, int columnStartPos){
int sumValuePrimary = 0;
int sumValueSecondaryRight= 0;
int sumValueSecondaryLeft= 0;
for(int i=0;i<=rowStartPos;i++){
sumValuePrimary += sortedMatrix[i][i];
if(i!=rowStartPos){
sumValueSecondaryRight+=sortedMatrix[i][i+1];
}
if(i!=0){
sumValueSecondaryLeft+=sortedMatrix[i][i-1];
}
}
System.out.println("Primary Total Is : "+sumValuePrimary+", Secondary Left Total Is : "+sumValueSecondaryLeft+", Secondary Right Total Is : "+sumValueSecondaryRight);
}```

#### hema

• Jan 3rd, 2015

```Codepackage testCode;

public class SquareMatrix {

public static void main(String[] args) {
int [][] squarematrix =  {
{ 1,1,1,10},
{ 1,10,-1,2},
{ 1,-2,1,2},
{ 1,1,1,-2}
};
int primryDiagonaSum = 0, secondaryDiagonalSum = 0;
int size = squarematrix.length -1;
for(int i = 0; i<squarematrix.length; i++){
primryDiagonaSum += squarematrix[i][i];
secondaryDiagonalSum+= squarematrix[i][size-i];
}
System.out.println(" Primary diagonal sum =" +primryDiagonaSum);
System.out.println(" Secondary diagonal sum =" + secondaryDiagonalSum);
}
}
```

#### hema

• Jan 3rd, 2015

Tested Java code

```Codepackage testCode;

public class SquareMatrix {
public static void main(String[] args) {
int [][] squarematrix =  {
{ 1,1,1,10},
{ 1,10,-1,2},
{ 1,-2,1,2},
{ 1,1,1,-2}
};
int primryDiagonaSum = 0, secondaryDiagonalSum = 0;
int size = squarematrix.length -1;
for(int i = 0; i<squarematrix.length; i++){
primryDiagonaSum += squarematrix[i][i];
secondaryDiagonalSum+= squarematrix[i][size-i];
}
System.out.println(" Primary diagonal sum =" +primryDiagonaSum);
System.out.println(" Secondary diagonal sum =" + secondaryDiagonalSum);
}
}
```

#### Kavya oleti

• Jan 22nd, 2017

If it is a square matrix order n
Primary diagonal
if(i==j)
{
sum+=a[i][j];
}
Secondary diagonal
if(i==(n-1)-j)
{
sum+=a[i][j];
}  