Java program to Transpose a Matrix

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

Core Java Example Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.