|
1 | 1 | package com.sbiswas001.twelveproject; |
2 | 2 |
|
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +/** |
| 6 | + * This class transposes a matrix. |
| 7 | + * Transpose of a matrix is formed by interchanging |
| 8 | + * the rows and columns of the matrix. |
| 9 | + * @author Sayan Biswas |
| 10 | + * @version 25.04.2022 |
| 11 | + */ |
3 | 12 | public class Transpose { |
| 13 | + /** |
| 14 | + * Stores the matrix |
| 15 | + */ |
| 16 | + private int[][] mat; |
| 17 | + |
| 18 | + /** |
| 19 | + * Stores order of matrix |
| 20 | + */ |
| 21 | + private int order; |
| 22 | + |
| 23 | + /** |
| 24 | + * Initializes instance variables |
| 25 | + */ |
| 26 | + private Transpose() { |
| 27 | + mat = null; |
| 28 | + order = 0; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Inputs number of rows and columns of a matrix |
| 33 | + * and the elements of the matrix. |
| 34 | + */ |
| 35 | + private void input() { |
| 36 | + Scanner sc = new Scanner(System.in); |
| 37 | + System.out.print("Enter order of the square matrix: "); |
| 38 | + order = Integer.parseInt(sc.nextLine()); |
| 39 | + mat = new int[order][order]; |
| 40 | + System.out.println("Enter the elements of the matrix: "); |
| 41 | + for(int i = 0; i < order; i++) { |
| 42 | + for(int j = 0; j < order; j++) { |
| 43 | + mat[i][j] = Integer.parseInt(sc.next()); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Transposes the matrix |
| 50 | + */ |
| 51 | + private void compute() { |
| 52 | + int temp; |
| 53 | + for(int i = 0; i < mat.length; i++) { |
| 54 | + for (int j = i; j < mat[0].length; j++) { |
| 55 | + temp = mat[i][j]; |
| 56 | + mat[i][j] = mat[j][i]; |
| 57 | + mat[j][i] = temp; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Prints a two-dimensional array |
| 64 | + * @param a The array to be printed |
| 65 | + */ |
| 66 | + private void display(int[][] a) { |
| 67 | + for(int i = 0; i < a.length; i++) { |
| 68 | + for(int j = 0; j < a[0].length; j++) { |
| 69 | + System.out.print(a[i][j]+" "); |
| 70 | + } |
| 71 | + System.out.println(); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * Calls other methods |
| 77 | + * @param args Arguments passed to main method |
| 78 | + */ |
| 79 | + public static void main(String[] args) { |
| 80 | + Transpose ob = new Transpose(); |
| 81 | + ob.input(); |
| 82 | + System.out.println("Entered matrix is: "); |
| 83 | + ob.display(ob.mat); |
| 84 | + ob.compute(); |
| 85 | + System.out.println("Transpose of matrix is "); |
| 86 | + ob.display(ob.mat); |
| 87 | + } |
4 | 88 | } |
0 commit comments