Untitled
unknown
plain_text
21 days ago
1.9 kB
1
Indexable
Never
import java.util.Scanner; public class tracetranspose { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows: "); int rows = scanner.nextInt(); System.out.print("Enter the number of columns: "); int cols = scanner.nextInt(); int[][] matrix = new int[rows][cols]; System.out.println("Enter the elements of the matrix:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print("Element [" + i + "][" + j + "]: "); matrix[i][j] = scanner.nextInt(); } } System.out.println("The matrix is:"); displayMatrix(matrix); if (rows == cols) { int trace = 0; for (int i = 0; i < rows; i++) { trace += matrix[i][i]; } System.out.println("Trace of the matrix: " + trace); } else { System.out.println("The matrix is not square, so trace is not defined."); } int[][] transpose = transposeMatrix(matrix); System.out.println("The transpose of the matrix is:"); displayMatrix(transpose); } private static void displayMatrix(int[][] matrix) { for (int[] row : matrix) { for (int elem : row) { System.out.print(elem + "\t"); } System.out.println(); } } private static int[][] transposeMatrix(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; int[][] transpose = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { transpose[j][i] = matrix[i][j]; } } return transpose; } }
Leave a Comment