Program opened below. You can scroll through the algorithm, Java code and output.
Program 32
Check Whether a Matrix Is Symmetric
Question
Accept a square two-dimensional array and determine whether it is symmetric.
Algorithm
Step 1: Start the program and accept the order n of the square matrix.
Step 2: Declare a square integer array of order n.
Step 3: Read each element of the matrix using nested loops.
Step 4: Assume initially that the matrix is symmetric.
Step 5: Select each matrix element A[i][j] using nested row and column loops.
Step 6: Compare the selected element with its corresponding element A[j][i].
Step 7: If the two elements differ, set the symmetry flag to false.
Step 8: Continue the comparisons for the remaining positions.
Step 9: After all comparisons, test the symmetry flag.
Step 10: If the flag remains true, report that the matrix is symmetric.
Step 11: Otherwise report that the matrix is not symmetric.
Step 12: Stop the program.
Java program
Javaimport java.util.*;
class SymmetricMatrix
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter order: ");
int n = sc.nextInt();
int[][] a = new int[n][n];
System.out.println("Enter matrix elements:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = sc.nextInt();
}
}
boolean symmetric = true;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[i][j] != a[j][i])
{
symmetric = false;
}
}
}
if (symmetric)
{
System.out.println("Matrix is symmetric");
}
else
{
System.out.println("Matrix is not symmetric");
}
}
}Sample output
Input: Input: 2; matrix: 1 2 / 2 3
Output: Matrix is symmetric