GeekInterview.com
Series: Subject: Topic:
Question: 28 of 51

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.
Asked by: wiseboy | Member Since Jan-2009 | Asked on: Jan 26th, 2009

View all questions by wiseboy

Showing Answers 1 - 2 of 2 Answers
Asher The King

Answered On : Jul 10th, 2011

View all answers by Asher The King

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

  
Login to rate this answer.
Ashima

Answered On : 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. for (int i = 0; i < row; i++)
  2.             {
  3.                 int j = 0;
  4.                 while (j < col)
  5.                 {
  6.                     //Primary diagonal
  7.                     if (i == j) sum += A[i][j];
  8.                     j++;
  9.                     //Secondary diagonal
  10.                     if (i == (col - j)) sum += A[i][j - 1];
  11.                 }
  12.             }

  
Login to rate this answer.

Give your answer:

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

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.