I’m having a problem printing columns. When the code reaches “100” it stops reading what is below it because it’s empty:
public class Column{
public static void main( String[] arg )
{
int[][] uneven =
{ { 1, 3, 100, 6, 7, 8, 9, 10},
{ 0, 2},
{ 0, 2, 4, 5},
{ 0, 2, 4, 6, 7},
{ 0, 1, 4, 5 },
{ 0, 1, 2, 3, 4, 5, 6 }};
for ( int col=0; col < uneven.length; col++ )
{
System.out.print("Col " + col + ": ");
for( int row=0; row < uneven.length; row++ )
System.out.print( uneven[row][col] + " ");
System.out.println();
}
}
}
What should I do so that it will continue reading the column?
To print a variable length 2-D array, your inner loop runs from
0tothe current rowlength : –arr[i]is the current row. Andarr[i].lengthgives the number of columns in that row.You can infer it like this: –
arris a 2-D array.arris a1-D array.arr[i]is a 1-D array. Which represents each row.arr[i].lengthNow, you can apply the same thing in your problem.
Actually, your
for loopis running wrongly. Yourouter loopis running fromcol = 0 to col < uneven.length, but it should run from: –row = 0 to row < uneven.lengthSo, your for loop should be like: –
UPDATED : –
Ok, I got your question wrong first. If you want to print
column wise, you can use this code: –First you need to find the max among all number of columns in each row.
Then run the loop again, from 0 to max columns. Now, since you have a lop for
columns, now you need another one forrows. And that will be your inner loop.Now, in inner loop, you cannot just print the array element at the
(j, i)index, because the current row might not havemaxnumber of columns. So, you need to put anif-conditionto check that.