Categories

# Symmetric Matrix in Java

Write a program to declare a square matrix a[][] of order M
×  M, where M is a positive integer and represents rows and columns for the matrix. M should be greater than 2 and less than 10. Accept the value of M from the user. Display an appropriate message for an invalid input.

Perform the following tasks:

1. Display the original matrix.
2. Check if the given matrix is symmetric or not. If each element in the ith row and jth column is same as element of jth row and ith column, then the matrix is symmetric.
3. Find the sum of the left and right diagonals of the matrix and display them.
Example 1:
INPUT:
M = 3
1 2 3
2 4 5
3 5 6
OUTPUT:
1 2 3
2 4 5
3 5 6
The given matrix is symmetric.
Sum of the left diagonal = 11
Sum of the right diagonal = 10

Example 2:
INPUT:
M = 4
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
OUTPUT:
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
The given matrix is not symmetric.
Sum of the left diagonal = 17
Sum of the right diagonal = 20

Example 3:
OUTPUT:
Matrix size is out of range.
import java.io.*;
class Symmetric{
public static void main(String args[])
throws IOException{
System.out.print("Matrix size: ");
int m = Integer.parseInt(br.readLine());
int ld = 0;
int rd = 0;
boolean flag = true;
if(m <= 2 || m >= 10){
System.out.println("Size out of range!");
return;
}
int a[][] = new int[m][m];
System.out.println("Enter matrix elements:");
for(int i = 0; i < m; i++){
for(int j = 0; j < m; j++){
if(i == j)
ld += a[i][j];
if(i + j == m - 1)
rd += a[i][j];
}
}
System.out.println("Original Matrix:");
for(int i = 0; i < m; i++){
for(int j = 0; j < m; j++){
System.out.print(a[i][j] + "\t");
if(a[i][j] != a[j][i])
flag = false;
}
System.out.println();
}
if(flag)
System.out.println("The matrix is symmetric.");
else
System.out.println("The matrix is not symmetric.");
System.out.println("Sum of left diagonal elements: " + ld);
System.out.println("Sum of right diagonal elements: " + rd);
}
}

This site uses Akismet to reduce spam. Learn how your comment data is processed.