10. Program to find the transpose of a given matrix
💡Code:
import java.util.Scanner;
public class MatrixTranspose7078 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the dimensions of the matrix from the user
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int columns = scanner.nextInt();
// Create the matrix
int[][] matrix = new int[rows][columns];
System.out.println("Enter elements for the matrix:");
inputMatrix(matrix, scanner);
// Find the transpose of the matrix
int[][] transposeMatrix = findTranspose(matrix);
// Display the original and transpose matrices
System.out.println("Original Matrix:");
displayMatrix(matrix);
System.out.println("Transpose Matrix:");
displayMatrix(transposeMatrix);
// Close the scanner
scanner.close();
}
// Function to input elements into a matrix
private static void inputMatrix(int[][] matrix, Scanner scanner) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print("Enter element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix[i][j] = scanner.nextInt();
}
}
}
// Function to find the transpose of a matrix
private static int[][] findTranspose(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
int[][] transposeMatrix = new int[columns][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
transposeMatrix[j][i] = matrix[i][j];
}
}
return transposeMatrix;
}
// Function to display the elements of a matrix
private static void displayMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
📸Output :