12. Program to Transpose matrix
💡Code:
import java.util.Scanner;
public class TransposeMatrix7078 {
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);
// Transpose the matrix
int[][] transposedMatrix = transposeMatrix(matrix);
// Display the original and transposed matrices
System.out.println("Original Matrix:");
displayMatrix(matrix);
System.out.println("Transposed Matrix:");
displayMatrix(transposedMatrix);
// 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 transpose a matrix
private static int[][] transposeMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
int[][] transposedMatrix = new int[columns][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
transposedMatrix[j][i] = matrix[i][j];
}
}
return transposedMatrix;
}
// 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 :