Reputation: 35
I need to display an array of numbers. The output needs to be this:
10 25 29 13 46 30 26 57 41 34 88 52 60 77 82
I currently have it working but its not displaying column-wise, here is my output:
10 13 26 34 60 25 46 57 88 77 29 30 41 52 82
I found a similar question with answer on here but it was for rows that aren't all the same length, so I don't think it will be helpful to use it.
Here is my code (also I'm new to java):
public class test
{
public static void main(String[] args)
{
int rows = 3;
int cols = 5;
int intar [][] = { {10, 13, 26, 34, 60} ,
{25, 46, 57, 88, 77},
{29, 30, 41, 52, 82} };
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print ( intar[i][j] + " " );
}
}
}
}
Upvotes: 1
Views: 3844
Reputation: 2288
Just replace your for loop with this
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print ( intar[j][i] + " " );
}
System.out.println();
}
Upvotes: 0
Reputation: 201439
You're close, it's
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(intar[j][i] + " ");
}
}
Upvotes: 0
Reputation: 3197
You can make a small change as follows:
From
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(intar[i][j] + " ");
}
}
To
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
System.out.print(intar[i][j] + " ");
}
}
Output in Console;
10 25 29 13 46 30 26 57 41 34 88 52 60 77 82
Upvotes: 5
Reputation: 11832
Switch the following two lines:
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
Upvotes: 1
Reputation: 328
Add a new line
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print ( intar[i][j] + " " );
}
System.out.print ( "\n" );
}
BTW You will also want to do padding
Upvotes: -1