A 2-D array corresponds to a mathematical matrix:
11 12 13 21 22 23 31 32 33
One simple matrix operation transposes the matrix elements:
11 21 31 12 22 32 13 23 33
// MatrixTranspose: This class shows how to transpose a 2D square matrix. // It's a complete solution for the example discussed // in lecture. import java.io.*; public class MatrixTranspose { public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader (System.in)); // User enters one dimension of the 2D array. System.out.print ("Enter array size: "); int size = Integer.parseInt(in.readLine()); System.out.println (" Array is " + size + "x" + size); // Create a 2D array. int[][] a = new int[size][size]; // User enters values, which are put into the array. System.out.print ("Enter " + size*size + " integer values"); System.out.println (" (one per line): "); for (int r = 0; r < a.length; r++) { for (int c = 0; c < a[0].length; c++) { a[r][c] = Integer.parseInt(in.readLine()); } } // Print original array. System.out.println ("Original array:"); for (int r = 0; r < a.length; r++) { for (int c = 0; c < a[0].length; c++) { System.out.print (a[r][c] + " "); } System.out.println(); } // Transpose array. int startc = 1; for (int r = 0; r < a.length; r++) { for (int c = startc; c < a[0].length; c++) { int temp = a[r][c]; a[r][c] = a[c][r]; a[c][r] = temp; } startc++; } // Print transposed array. System.out.println ("Transposed array:"); for (int r = 0; r < a.length; r++) { for (int c = 0; c < a[0].length; c++) { System.out.print (a[r][c] + " "); } System.out.println(); } } }
Enter array size: 3 Array is 3x3 Enter 9 integer values (one per line): 6 7 8 4 3 1 2 9 5 Original array: 6 7 8 4 3 1 2 9 5 Transposed array: 6 4 2 7 3 9 8 1 5