Print All Diagonals of a given matrix

Objective: Given two dimensional matrix, write an algorithm to print all the diagonals of matrix.

Example:
Print All Diagonals of Matix 2

Approach:

We will solve this problem in two parts. first half of diagonals and second half of diagonals.

See the code for more understanding, its self explanatory.

Complete Code:

public class Diagonals {
public static void print(int [][] a){
//print first half
int row =0;
int col;
while(row<a.length){
col =0;
int rowTemp = row;
while(rowTemp>=0){
System.out.print(a[rowTemp][col] + " ");
rowTemp;
col++;
}
System.out.println();
row++;
}
//print second half
col = 1;
while(col<a.length){
int colTemp = col;
row = a.length1;
while(colTemp<=a.length1){
System.out.print(a[row][colTemp] + " ");
row;
colTemp++;
}
System.out.println();
col++;
}
}
public static void main(String[] args) {
int [][] a = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
print(a);
}
}

view raw
Diagonals.java
hosted with ❤ by GitHub

Output:

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