Reputation: 2716
I have the below code for printing a two-dimensional array. I would like to print rows and columns in this array alternately.
public class TwoDimensionalArrays {
public static void main(String[] args) {
int marks[][]={{1,2,3},{4,5,6},{7,8,9}};
for(int j=0;j<marks[0].length;j++) {
for(int i=0;i<marks.length;i++) {
}
}
}
This is how I'd like my output to look.
1 2 3
1 4 7
5 6
5 8
9
How can I tackle this?
Upvotes: 0
Views: 83
Reputation: 1591
The key is setting i = j
in the nested for loops
for (int j = 0; j < marks.length; j++) {
for (int i = j; i < marks[j].length; i++) {
System.out.print(marks[j][i] + " ");
}
System.out.println();
if (j == marks.length - 1)
break;
for (int i = j; i < marks.length; i++) {
System.out.print(marks[i][j] + " ");
}
System.out.println();
}
Upvotes: 1
Reputation: 1059
This works. Lots of confusing i's and j's, but it outputs what you want.
public static void main(String[] args)
{
int marks[][]={{1,2,3},{4,5,6},{7,8,9}};
for(int j = 0; j < marks[0].length; j++)
{
//Row across
for(int i = j; i < marks.length; i++)
{
System.out.print(marks[j][i] + " ");
}
System.out.println();
//Column down
if (j != marks[0].length - 1) //so we don't print 9 twice
{
for(int i = j; i < marks.length; i++)
{
System.out.print(marks[i][j] + " ");
}
System.out.println();
}
}
}
Upvotes: 0
Reputation: 3151
This is a solution that will print what you need. Please be aware that you might need to do something with that ArrayIndexOutOfBoundsException
for(int j=0;j<marks[0].length;j++) {
System.out.println();
for(int i=0;i<marks.length;i++) {
try {
System.out.print(marks[j][i+j]);
} catch (ArrayIndexOutOfBoundsException e) {
//do nothing
}
}
System.out.println();
for(int i=0;i<marks.length;i++) {
try {
if(j < marks.length-1) {
System.out.print(marks[i + j][j]);
}
} catch (ArrayIndexOutOfBoundsException e) {
//do nothing
}
}
}
Upvotes: 0