import java.util.Scanner; public class Array_2D_Transpose { public static int[][] transpose(int[][] ar) { int row = ar.length; int col = ar[0].length; int nar[][] = new int[col][row]; for (int i = 0; i < nar.length; i++) //decides number of rows... so taken new array (nar) { for (int j = 0; j < nar[i].length; j++) { nar[i][j] = ar[j][i]; } } return nar; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the Outer Array size : "); int rows = sc.nextInt(); System.out.println("Enter the Inner Array size : "); int col = sc.nextInt(); int ar[][] = new int[rows][col]; for (int i = 0; i < ar.length; i++) { for (int j = 0; j < ar[i].length; j++) { System.out.println("enter the value ar "+i+"th row and"+j+"the column"); ar[i][j] = sc.nextInt(); } } System.out.println("The array elements are :-"); for (int i = 0; i < ar.length; i++) { for (int j = 0; j < ar[i].length; j++) { System.out.print(ar[i][j]+" "); } System.out.println(); } int nar1[][] = transpose(ar); System.out.println("The array elements after TRANSPOSE :-"); for (int i = 0; i < nar1.length; i++) { for (int j = 0; j < nar1[i].length; j++) { System.out.print(nar1[i][j]+" "); } System.out.println(); } } }
Output:-
Enter the Outer Array size :
3
Enter the Inner Array size :
3
enter the value ar 0th row and0the column
1
enter the value ar 0th row and1the column
2
enter the value ar 0th row and2the column
3
enter the value ar 1th row and0the column
4
enter the value ar 1th row and1the column
5
enter the value ar 1th row and2the column
6
enter the value ar 2th row and0the column
7
enter the value ar 2th row and1the column
8
enter the value ar 2th row and2the column
9
The array elements are :-
1 2 3
4 5 6
7 8 9
The array elements after TRANSPOSE :-
1 4 7
2 5 8
3 6 9