In this tuotrial, we will write a program which accepts element of a matrix from user and display its transpose.
Matrix is a two-dimensional array which represents several rows and columns of data.
A two-dimensional array is represented as:
int[][] arr
Transpose of a matrix is just interchanging rows and columns with each other.
Now in this code solution, we will accept input from user and will display its transpose.
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []args){
//using scanner class to take input from user
Scanner sc = new Scanner(System.in);
//accept rows and columns of matrix
System.out.println("Enter rows, columns: ");
//r denotes row, c denotes columns
int r = sc.nextInt();
int c = sc.nextInt();
//creating array with size of r and c
int[][]arr=new int[r][c];
//accepting matrix from keyboard
System.out.println("Enter elements of matrix: ");
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
arr[i][j]=sc.nextInt(); //elements has been taken
System.out.println("Transpose of entered matrix: ");
//taking rows and columns vice versa and then display
for(int i=0; i<c; i++)
{
for(int j=0; j<r; j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}
}
}
Output:
Enter rows, columns:
2 2
Enter elements of matrix:
1 2
3 4
Transpose of entered matrix:
1 2
3 4
Also read:
- Creating and closing a frame in JAVA (Click Listener)
- Program to Calculate a factorial of a number without using Recurion method
- Reverse a String using StringBuffer class