transpose array:

Transposing a two-dimensional array means converting its rows into columns and its columns into rows. Essentially, it is a reflection of the original array along its main diagonal.

For example, given the following 2D array:

1 2 3

4 5 6

7 8 9

The transpose of this array would be:

1 4 7

2 5 8

3 6 9

Each element at index [i][j] in the original array becomes the element at index [j][i] in the transposed array.


Here's a Java program to find the transpose of a two-dimensional array:


public class TransposeArray
public static void main(String[] args) {
// Step 1: Define a two-dimensional array 
int[][] matrix = { 
 {1, 2, 3},
 {4, 5, 6}, 
 {7, 8, 9} }; 
// Step 2: Find the transpose of the array 
int[][] transposeMatrix = transpose(matrix); 
// Step 3: Print the transpose of the array 
 System.out.println("Transpose of the array: ");
for (int i = 0; i < transposeMatrix.length; i++) 
{
for (int j = 0; j < transposeMatrix[i].length; j++) 
 System.out.print(transposeMatrix[i][j] + " ");
 } 
 System.out.println();
 }
 } 
// Function to find the transpose of the array
public static int[][] transpose(int[][] arr) {
// Step 4: Create a new array to store the transpose 
int rows = arr.length; 
int cols = arr[0].length; 
int[][] transposeMatrix = new int[cols][rows]; 
// Step 5: Find the transpose by swapping rows and columns
for (int i = 0; i < rows; i++) { 
for (int j = 0; j < cols; j++) { 
 transposeMatrix[j][i] = arr[i][j]; 
 } 
 } 
// Step 6: Return the transpose array 
return transposeMatrix; } 
}

Explanation of each step:

  1. We start by defining a two-dimensional array named matrix. In this example, we have a 3x3 matrix with elements { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }.
  2. We call the function transpose(matrix) to find the transpose of the array matrix.
  3. We then print the transpose of the array using nested loops. The outer loop iterates through the rows, and the inner loop iterates through the columns to print each element of the transpose.
  4. The function transpose takes a two-dimensional array as input and returns the transpose of that array.
  5. Inside the function, we create a new two-dimensional array named transposeMatrix to store the transpose. The number of rows and columns in the transpose are swapped from the original array (rows become cols and vice versa).
  6. We use nested loops to find the transpose. For each element at index [i][j] in the original array, we place it at index [j][i] in the transposeMatrix. This effectively transposes the elements of the original array.
  7. After finding the transpose, we return the transposeMatrix.


When you run this program with the provided 3x3 matrix, it will output:

Transpose of the array: 

1 4 7 

2 5 8 

3 6 9 

This is the transpose of the original matrix, where the rows and columns have been swapped. If you modify the matrix to have different elements or dimensions, the program will find and display the transpose accordingly.