Symmetric matrix program in java

Today we are going to learn symmetric matrix program in java.

A square matrix is said to be symmetric if given square matrix is equal to its transpose.

How do you know whether a matrix is symmetric or not?

For a matrix to be symmetric, first it should be a square matrix and second every element at “i”th row and “j”th column should be equal to every element at “j”th row and “i”th column.

symmetric matrix program in java

In other words A[x][y] is a square matrix of (3 X 3) order, then A[x][y] matrix is said to be symmetric if every element at “x”th row and “y”th column is equal to element at “y”th row and “x”th column.

Also read – transpose of a matrix

That is A[x][y] == A[y][x]

Let’s see java program to check if the matrix is symmetric or not,

import java.util.Scanner;

public class SymmetricMatrixDemo
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of rows - ");
      int row = sc.nextInt();
      System.out.println("Please enter number of columns - ");
      int col = sc.nextInt();
      int symMatrix[][] = new int[row][col];     
      System.out.println("Please enter the elements - ");

      for(int x = 0; x < row; x++)
      {
         for(int y = 0; y < col; y++)
         {
            symMatrix[x][y] = sc.nextInt();
         }
      }

      System.out.println("Now printing the input matrix - ");
      for(int x = 0; x < row; x++)
      {
         for(int y = 0; y < col; y++)
         {
            System.out.print(symMatrix[x][y] + "\t");
         }
         System.out.println();
      }

      // Now checking for symmetric matrix
      if(row != col)
      {
         System.out.println("It's not a square matrix!!");
      }
      else
      {
         boolean symmetricMatrix = true;
         for(int x = 0; x < row; x++)
         {
            for(int y = 0; y < col; y++)
            {
               if(symMatrix[x][y] != symMatrix[y][x])
               {
                  symmetricMatrix = false;
                  break;
               }
            }
         }

         if(symmetricMatrix)
         {
            System.out.println("It's a symmetric matrix!!");
         }
         else
         {
            System.out.println("It's not a symmetric matrix!!");
         }
      }
      sc.close();
   }
}

Output:

Please enter number of rows – 3
Please enter number of columns – 3
Please enter the elements –
2 4 6 4 1 8 6 8 10
Now printing the input matrix –
2 4 6
4 1 8
6 8 10
It’s a symmetric matrix!!


Also read – sparse matrix and its representation in java