I wrote the following code to walk half the diagonals of an array:
String[][] b = [a,b,c]
[d,e,f]
[g,h,i];
public void LoopD
As Alex mentioned here, you need to look into indices in the loop. The following is how I approached this problem.
Input:
a b c ----- (0,0) (0,1) (0,2)
d e f ----- (1,0) (1,1) (1,2)
g h i ----- (2,0) (2,1) (2,2)
Output:
a ----- (0,0)
b d ----- (0,1) (1,0)
c e g ----- (0,2) (1,1) (2,0)
f h ----- (1,2) (2,1)
i ----- (2,2)
public class PrintDiagonal{
public static void printDR(String[][] matrix, int rows, int cols){
for(int c=0; c < cols; c++){
for(int i=0, j=c; i< rows && j>=0;i++,j--){
System.out.print(matrix[i][j] +" ");
}
System.out.println();
}
for(int r =1; r < rows; r++){
for(int i =r, j= cols -1; i=0; i++,j--){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args){
String[][] matrix ={
{"a","b","c"},
{"d","e","f"},
{"g","h","i"}
};
int rows = matrix.length;
int columns = matrix[0].length;
printDR(matrix ,rows, columns);
}
}