Given a matrix of order N*N, write code to print both the diagonals of that matrix. For example: the matrix and its 2 diagonals are given below:

In the above diagram, I have colored the elements in first diagonal as red and elements in 2nd diagonal as green.

### Solution:

Here is another problem on printing elements of a matrix I posted earlier that prints the elements in diagonal order.

**Printing first diagonal (Red):**

All the elements of first diagonals are at (i,i) positions, do it is easy to print the first diagonal

for(int i=0; i<n; i++) cout << arr[i][i];

Note that some of my students have written the code like this:

for(int i=0; i<n; i++) for(int j=0; j<n; j++) if(i==j) cout << arr[i][j];

But, this is unnecessarily traversing all the elements of the matrix (even elements which are not diagonal). Hence the complexity of this code is O(n^{2}). Where as the code above (with one loop) takes O(n) time.

**Printing Second diagonal (Green):**

The elements in the second diagonal are at following positions

(3,0) (2,1) (1,0) (0,3)

or, if I generalize:

(n-1, 0) (n-2, 1) ….. (0, n-1)

Hence, the code will be:

for(int i=0; i<n; i++) cout << arr[n-1-i][i];

**The complete code** (function) which will print both the diagonals will be

#define N 4 void printdiagonal(int arr[N][N]) { cout<< "First Diagonal :"; for(int i=0; i<N; i++) cout << arr[i][i]; cout<< "SecondDiagonal :"; for(int i=0; i<N; i++) cout << arr[N-i-1][i]; }

Feel free to post your feedback / comment

———————————————————

superb ðŸ™‚