Write a program to declare a square matrix A[][] of order MxM where ‘M’ is the number of rows and the number of columns, such that M must be greater than 2 and less than 10. Accept the value of M as user input. Display an appropriate message for an invalid input. Allow the user to input integers into this matrix. Perform the following tasks:
a) Display the original matrix.
b) Check if the given matrix is symmetric or not. A square matrix is said to be symmetric, if the element in the ith row and jth column is equal to the element of the jth row and ith column.
c) Find the sum of the elements of left diagonal and the sum of the elements of right diagonal of the matrix and display them.
Test your program for the following data and some random data:
Example 1
INPUT: M= 3
1 2 3
2 4 5
3 5 6
OUTPUT:
ORIGINAL MATRIX
1 2 3
2 4 5
3 5 6
THE GIVEN MATRIX IS SYMMETRIC
The sum of the left diagonal = 11 The 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:
ORIGINAL MATRIX
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
THE GIVEN MATRIX IS NOT SYMMETRIC
The sum of the left diagonal = 17 The sum of the right diagonal = 20
Example 3
INPUT: M= 12
OUTPUT:
THE MATRIX SIZE IS OUT OF RANGE
import java.util.*;
public class SymmetricMatrix
{
int max[][];
int m;
Scanner sc=new Scanner(System.in);
public SymmetricMatrix()
{
m=3;
max=new int[m][m];
//{{1,2,3},{2,4,5},{3,5,6};
}
void input()
{
System.out.println("Enter the number of rows and columns:");
m=sc.nextInt();
if(m>2&&m<10)
{
max=new int[m][m];
System.out.println("Enter the elements for "+ m+ " rows "+ m+" columns");
for(int i=0;i<m;i++) //entering matrix elements
{
for(int j=0;j<m;j++)
{
max[i][j]=sc.nextInt();
}
}
}
else
System.out.println("THE GIVEN MATRIX IS NOT SYMMETRIC");
}
void display()
{
System.out.println("\nMATRIX");
for(int i=0;i<m;i++) //displaying the original matrix
{
for(int j=0;j<m;j++){
System.out.print(max[i][j]+"\t");
}
System.out.println();
}
}
public void isSymetric()
{
int flag=0;
for(int i=0;i<m;i++) //checking for symmetric matrix
{
for(int j=0;j<m;j++)
{
if(max[i][j]!=max[j][i])
{
flag=1;
break;
}
}
}
if(flag==0)
System.out.println("THE GIVEN MATRIX IS SYMMETRIC");
else
System.out.println("THE GIVEN MATRIX IS NOT SYMMETRIC");
}
void sumDiagonal()
{
int suml=0,sumr=0;
for(int i=0;i<m;i++) //finding sum of left diagonal
{
suml+=max[i][i];
}
int j=m-1;
for(int i=0;i<m;i++,j--) //finding sum of right diagonal
{
sumr+=max[i][j];
}
System.out.println( "Sum of left diagonal = "+suml);
System.out.println( "Sum of right diagonal = "+sumr);
}
public static void main(String args[])
{
SymmetricMatrix ob = new SymmetricMatrix();
ob.input();
ob.display();
ob.isSymetric();
ob.sumDiagonal();
}
}