# Print All Diagonals of a given matrix

Objec­tive: Given two dimen­sional matrix, write an algo­rithm to print all the diag­o­nals of matrix.

Exam­ple:

Approach:

We will solve this prob­lem in two parts. first half of diag­o­nals and sec­ond half of diagonals.

See the code for more under­stand­ing, its self explanatory.

Com­plete Code:

Out­put:

```1
5 2
9 6 3
13 10 7 4
14 11 8
15 12
16
```

#### You may also like...

• zsal­abc

pub­lic sta­tic void print(int[][] a) {
int start­Col­umn = 0;
int las­tRow = a.length-1;
for (int r = 0; r < a.length || start­Col­umn = a.length) {
dr = las­tRow;
start­Col­umn++;
}
for (int c = start­Col­umn; c
= 0; c++) {
System.out.print(“ “+a[dr–]);
}
System.out.println();
}
}

• Pra­teek Gupta

Sim­ple Solu­tion:
pub­lic sta­tic void print(int[][] a) {
int m=a.length;
int n=a[0].length;
for(int i=0;i=m-1)x=m-1;
int y=i-x;
while(x>=0 && y<n && x=0){
System.out.print(a[x][y]+” ”);
x–;y++;
}
System.out.println();
}
}

• Hec­torGuo

There is an another solu­tion that just loop the matrix (don’t need to con­sider half and half):

func­tion diagonalPrint(matrix) {
const len = matrix.length;
let output = {};

// sum of index in every diag­o­nal is the same
// 0 — 00
// 1 — 01 10
// 2 — 02 11 20
// 3 — 03 12 21 30
for(let i = 0; i < len; i++) {
for(let j = 0; j < len; j++) {
if(!output[i+j]) {
output[i+j] = [];
}
output[i+j].push(matrix[j][i]); // loop by col­umn, matrix[i][j] — loop by row
}
}

return out­put;
}

// out­put
{
0: [1],
1: [5, 2],
2: [9,6, 3],

}