Q:

Java program to Transpose a Matrix

0

Java program to Transpose a Matrix

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Java program for Transposing a Matrix - It's an Example of Two Dimensional Array in Java, in this program we will read a matrix and print it's transpose matrix.

//Java program to print Transpose Matrix.

import java.util.*;

public class TransposeMatrix {
  public static void main(String args[]) {
    int row, col;

    Scanner sc = new Scanner(System.in);

    //Read number of rows and cols
    System.out.print("Input number of rows: ");
    row = sc.nextInt();
    System.out.print("Input number of rows: ");
    col = sc.nextInt();

    //declare two dimensional array (matrices)
    int a[][] = new int[row][col];

    //Read elements of Matrix a
    System.out.println("Enter elements of matrix a:");
    for (int i = 0; i < row; i++) {
      for (int j = 0; j < col; j++) {
        System.out.print("Element [" + (i + 1) + "," + (j + 1) + "] ? ");
        a[i][j] = sc.nextInt();
      }
    }

    //print matrix a
    System.out.println("Matrix a:");
    for (int i = 0; i < row; i++) {
      for (int j = 0; j < col; j++) {
        System.out.print(a[i][j] + "\t");
      }
      System.out.print("\n");
    }

    //print matrix b
    System.out.println("::: Transpose Matrix ::: ");
    for (int i = 0; i < col; i++) {
      for (int j = 0; j < row; j++) {
        System.out.print(a[j][i] + "\t");
      }
      System.out.print("\n");
    }
    
  }
}

Output:

    me@linux:~$ javac TransposeMatrix.java 
    me@linux:~$ java TransposeMatrix 

    Input number of rows: 2
    Input number of rows: 3
    Enter elements of matrix a:
    Element [1,1] ? 1
    Element [1,2] ? 2
    Element [1,3] ? 3
    Element [2,1] ? 4
    Element [2,2] ? 5
    Element [2,3] ? 6
    Matrix a:
    1	2	3	
    4	5	6	
    ::: Transpose Matrix ::: 
    1	4	
    2	5	
    3	6

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Core Java Example programs for Beginners and Professionals

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to print ODD numbers from 1 to N... >>
<< Java program to add two matrices...