ADVERTISEMENT
ADVERTISEMENT

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:

    [email protected]:~$ javac TransposeMatrix.java 
    [email protected]:~$ 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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.