‹ Back to the paper
A class Trans is defined to find the transpose of a square matrix. A transpose of a matrix is…
A class Trans is defined to find the transpose of a square matrix. A transpose of a matrix is obtained by interchanging the elements of the rows and columns.
Example: If size of the matrix = 3, then
Some of the members of the class are given below:
Specify the class Trans giving details of the constructor( ), void fillarray( ), void transpose( ) and void display(). Define a main() function to create an object and call the functions accordingly to enable the task.
| ORIGINAL | TRANSPOSE | ||||
|---|---|---|---|---|---|
| 11 | 5 | 7 | 11 | 8 | 1 |
| 8 | 13 | 9 | 5 | 13 | 6 |
| 1 | 6 | 20 | 7 | 9 | 20 |
| Class name | : | Trans |
|---|---|---|
| **Data members/instance variables:** | ||
| arr[ ][ ] | : | to store integers in the matrix |
| m | : | integer to store the size of the matrix |
| **Methods / Member functions:** | ||
| Trans(int mm) | : | parameterised constructor to initialise the data member $m = mm$ |
| void fillarray( ) | : | to enter integer elements in the matrix |
| void transpose( ) | : | to create the transpose of the given matrix |
| void display( ) | : | displays the original matrix and the transposed matrix by invoking the method transpose() |
Answer
Answer
AIimport java.util.Scanner;
class Trans
{
static Scanner sc = new Scanner(System.in);
int arr[][]; // the matrix
int m; // size of the matrix
// parameterised constructor
Trans(int mm)
{
m = mm;
arr = new int[m][m];
}
// accepts the elements of the matrix
void fillarray()
{
System.out.println("Enter " + (m * m) + " elements:");
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
arr[i][j] = sc.nextInt();
}
// transposes the matrix in place by swapping arr[i][j] and arr[j][i]
void transpose()
{
for (int i = 0; i < m; i++)
{
for (int j = i + 1; j < m; j++)
{
int t = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = t;
}
}
}
// prints the matrix row by row
void print()
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
System.out.print(arr[i][j] + "\t");
System.out.println();
}
}
// displays the original matrix, then the transposed matrix
void display()
{
System.out.println("ORIGINAL MATRIX");
print();
transpose();
System.out.println("TRANSPOSE");
print();
}
public static void main(String args[])
{
System.out.print("Enter the size of the matrix: ");
int size = sc.nextInt();
Trans ob = new Trans(size);
ob.fillarray();
ob.display();
}
}transpose() swaps each element above the main diagonal with its mirror element below it (arr[i][j] with arr[j][i]), so rows become columns. display() prints the original matrix, invokes transpose() and prints the result.
Sample run:Enter the size of the matrix: 3
Enter 9 elements:
11 5 7
8 13 9
1 6 20
ORIGINAL MATRIX
11 5 7
8 13 9
1 6 20
TRANSPOSE
11 8 1
5 13 6
7 9 20 From ISC 2023 Computer Science Paper 1, question 7.