CJ_Slip_6B

Slip No.2

B) Write a java program to display transpose of a given matrix.

1. Open Notepad.

2. Type the following code:

    import java.util.Scanner;

    public class MatrixTranspose {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number of rows and columns
    System.out.print("Enter the number of rows: ");
    int rows = scanner.nextInt();
    System.out.print("Enter the number of columns: ");
    int columns = scanner.nextInt();

    // Initialize the matrix and input elements
    int[][] matrix = new int[rows][columns];
    System.out.println("Enter the elements of the matrix:");
    for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
    matrix[i][j] = scanner.nextInt();
    }
    }

    // Display original matrix
    System.out.println("Original Matrix:");
    displayMatrix(matrix);

    // Calculate and display transpose
    int[][] transpose = new int[columns][rows];
    for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
    transpose[j][i] = matrix[i][j];
    }
    }
    System.out.println("\nTranspose Matrix:");
    displayMatrix(transpose);
    }

    // Method to display a matrix
    public static void displayMatrix(int[][] matrix) {
    for (int[] row : matrix) {
    for (int value : row) {
    System.out.print(value + " ");
    }
    System.out.println();
    }
    }
    }


3. Save the file with the name MatrixTranspose.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Open the Command Prompt.

5. Compile the Java program by typing:
javac MatrixTranspose.java

6. Run the compiled Java program by typing:
java MatrixTranspose

7. output:
Enter the number of rows: 3
Enter the number of columns: 4
Enter the elements of the matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Transpose Matrix:
1 5 9
2 6 10
3 7 11
4 8 12

No comments:

Post a Comment