127. JAVA Program to check given matrix is Symmetric or not.
How does this program work?
- In this program we are going to learn about how to check given matrix is Symmetric or not using java.
- Symmetric matrix means Original matrix and Transpose of the given matrix should be in equal.
- Find the Transpose of the given matrix.
- After that to check these two matrices are equal or not, If these are equal it is Symmetric else it is not Symmetric matrix.
Here is the code
//To check given matrix is Symmetric or not
import java.util.Scanner;public class Symmetric
{
public static void main(String[] args )
{
Scanner skill = new Scanner( System.in);
System.out.println( "Enter the number of rows :");
int rows = skill.nextInt();
System.out.println("Enter the number of columns :");
int cols = skill.nextInt();
int matrix[][] = new int[rows][cols];
System.out.println("Enter the elements :");
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < cols; j++ )
{
matrix[i][j] = skill.nextInt();
}
}
System.out.println("The input matrix is :");
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < cols; j++ )
{
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
//Checking the input matrix for symmetric
if ( rows != cols ){
System.out.println("The given matrix is not a square matrix, so it can't be symmetric.");
}
else
{
boolean symmetric = true;
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < cols; j++ )
{
if ( matrix[i][j] != matrix[j][i] )
{
symmetric = false;
break;
}
}
}
if ( symmetric)
{
System.out.println("The given matrix is symmetric.");
}
else
{
System.out.println("The given matrix is not symmetric.");
}
}
skill.close();
}
}