# two dimensional arrays

• 11-06-2010, 12:23 AM
cliffh
two dimensional arrays
I have created a two dimensional array that gets the number of rows, columns, number to start with, and how much to count by :
int [][] matrix = new int[r][c];
for (int i = 0; i<r; i++) {
for (int j = 0; j<c; j++){
matrix [i][j] = starting;
starting= starting + count;
System.out.print(matrix[i][j] + " ");

}
System.out.println();

}

Which prints out:
Original matrix:
2 6 10 14 18
22 26 30 34 38
42 46 50 54 58

How do I change this so the rows are printed as columns and the columns are printed as rows? So it prints:

Transposition matrix:
2 22 42
6 26 46
10 30 50
14 34 54
18 38 58
• 11-06-2010, 12:31 AM
Fubarable
Don't print out the results in the same nested for loops where you fill your array. Instead fill the array first, then use a new set of nested for loops to print out your array values, but in this second set of for loops, you'll reverse the order of the loops -- the outer loop will loop on the columns and the inner loop on the rows.
• 11-06-2010, 12:43 AM
cliffh
Perfect! Thanks a bunch!

int [][] matrix = new int[r][c];
for (int i = 0; i<r; i++) {
for (int j = 0; j<c; j++){
matrix [i][j] = starting;
starting= starting + count;
}

}

for (int i = 0; i<r; i++) {
for (int j = 0; j<c; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();

}
System.out.println("");
System.out.println("Transposition matrix:");
for (int j = 0; j<c; j++){
for (int i = 0; i<r; i++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}