
how to write transpose of a matrix a program....

public class Transpose {
public static void main(String[] args) {
// create N-by-N matrix
int N = Integer.parseInt(args[0]);
int[][] a = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
a[i][j] = N*i + j;
}
}
// print out initial matrix
System.out.println("Before");
System.out.println("------");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.printf("%4d", a[i][j]);
}
System.out.println();
}
// transpose in-place
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
// print out transposed matrix
System.out.println();
System.out.println("After");
System.out.println("------");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.printf("%4d", a[i][j]);
}
System.out.println();
}
}
}

import java.util.*;
public class Transpose {
public static void main(String[] args) throws Exception {
int rows, cols;
int[][] matrix, tmatrix;
Scanner input = new Scanner(System.in);
System.out.print("Enter number of rows: ");
rows = input.nextInt();
System.out.print("Enter number of columns: ");
cols = input.nextInt();
matrix = new int[rows][cols];
tmatrix = new int[cols][rows];
System.out.println("Enter elements for Matrix");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = input.nextInt();
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
tmatrix[i][j] = matrix[j][i];
}
}
System.out.println("Matrix is:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Its transpose is: ");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(tmatrix[i][j] + " ");
}
System.out.println();
}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.