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.

Questions by wiseboy

Showing Answers 1 - 6 of 6 Answers

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];
     }

  Was this answer useful?  Yes

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.

Code
  1. span style="font-style: italic;">//Primary diagonal//Secondary diagonal

JosephVP

  • Jul 24th, 2014
 

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

Code
  1. span style="color: #ff0000;">"Primary Total Is : "+sumValuePrimary+", Secondary Left Total Is : "+sumValueSecondaryLeft+", Secondary Right Total Is : "+sumValueSecondaryRight);

  2.         }



  Was this answer useful?  Yes

hema

  • Jan 3rd, 2015
 

Code
  1. span style="color: #006699;">testCode" Primary diagonal sum ="" Secondary diagonal sum =" + secondaryDiagonalSum);

  2.         }

  3.         }

  4.  

  Was this answer useful?  Yes

hema

  • Jan 3rd, 2015
 

Tested Java code

Code
  1. span style="color: #006699;">testCode" Primary diagonal sum ="" Secondary diagonal sum =" + secondaryDiagonalSum);

  2.         }

  3.         }

  4.  

  Was this answer useful?  Yes

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];
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions