Slip No 6 Q B

Q. Write a java program to display transpose of a given matrix.[25 M]

import java.util.Scanner;

public class MatrixTranspose {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of rows: ");
        int r = sc.nextInt();

        System.out.print("Enter number of columns: ");
        int c = sc.nextInt();

        int[][] a = new int[r][c];

        // Accept matrix elements
        System.out.println("Enter matrix elements:");
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                a[i][j] = sc.nextInt();
            }
        }

        // Display original matrix
        System.out.println("\nOriginal Matrix:");
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }

        // Display transpose matrix
        System.out.println("\nTranspose Matrix:");
        for(int i = 0; i < c; i++) {
            for(int j = 0; j < r; j++) {
                System.out.print(a[j][i] + " ");
            }
            System.out.println();
        }

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top