Symmetric matrix Write a static method which takes a 2-dimensional array of type
ID: 3565745 • Letter: S
Question
Symmetric matrix
Write a static method which takes a 2-dimensional array of type int, which represents a matrix, as its argument, and returns true if the matrix is symmetric and false otherwise. A matrix is symmetric if the entry at row i and column j is the same as the entry at row j and column i for each i and j. The diagonal entries (i.e. entries with the same row and column) can be any number.
Write a driver file to test your method. It should call your method with at least three different inputs.
Explanation / Answer
public class SymmetricMatrix
{
public static void main(String args[ ])
{
int i, j, flag = 0;
int matrixArgument1[][]= new int[][]{
{ 1, 2, 3},
{ 2, 1, 2},
{ 3, 4, 3}};
int matrixArgument2[][]= new int[][]{
{ 1, 2, 3},
{ 9, 1, 2},
{ 3, 4, 9}};
int matrixArgument3[][]= new int[][]{
{ 1, 2, 3},
{ 9, 1, 4},
{ 3, 6, 9}};
System.out.println(" Matrix 1 is : ");
print(matrixArgument1);
checkSymmetric(matrixArgument1);
System.out.println(" Matrix 2 is : ");
print(matrixArgument2);
checkSymmetric(matrixArgument2);
System.out.println(" Matrix 3 is : ");
print(matrixArgument3);
checkSymmetric(matrixArgument3);
}
public static void print(int matrix[][]){
for (int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
System.out.print(" "+matrix[i][j]+" ");
System.out.println();
}
}
public static void checkSymmetric(int matrix[][]){
int flag=0;
for (int i=0;i<3;i++)
for(int j=0;j<3;j++)
if (matrix[i][j] != matrix[j][i])
flag = 1;
if (flag == 1)
System.out.println(" Matrix is not symmetric");
else
System.out.println(" Matrix is symmetric");
}
}
****************Sample Output******************************
Compiling the source code....
$javac SymmetricMatrix.java 2>&1
Executing the program....
$java -Xmx128M -Xms16M SymmetricMatrix
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.