Problem Statement
To find the transpose, diagonal sum of a given matrix and check whether the matrix is symmetric or not.
Algorithm
1) Start.
2) Read n.
3) Allocate memory for matrix a[n][n],b[n][n]
4) Repeat step 5 for i=0 to n.
5) Repeat steps 6 through 7 for j=0 to n.
6) Read the matrix a[i][j].
7) Set b[j][i]=a[i][j].
8) Repeat step 9 for i=0 to n.
9) Repeat step 10 for j=0 to n.
10) Display b[i][j].
11) Repeat step 12 for i=0 to n.
12) Repeat step 13 for j=0 to n.
13) If a(i, j)!=b(i, j ) go to step 14.
14) If i=n and j=n then step go to 17.
15) Print ‘Matrix is Asymmetric’.
16) Got to 18.
17) Print ‘Matrix is Symmetric’.
18) Set d1=0,d2=0.
19) Repeat step 20 for i=0 to n.
20) Repeat steps 21 through 22 for j=0 to n.
21) If (i=j) then d1=d1+a[i][j].
22) If (i+j=n-1) then d2=d2+a[i][j].
23) Display d1, d2.
24) Stop.
Program
import java.io.DataInputStream; public class MatTranSymm { public static void main(String args[]) { DataInputStream in= new DataInputStream(System.in); int a[][]=null; int b[][]=null; int i,j=0,n=0,d1=0,d2=0; try { System.out.println("\nEnter the size of the square matrix : "); n=Integer.parseInt(in.readLine()); a=new int[n][n]; b=new int[n][n]; System.out.println("\nEnter the elements of the matrix : "); for(i=0;i<n;i++) for(j=0;j<n;j++) { a[i][j]=Integer.parseInt(in.readLine()); b[j][i]=a[i][j]; } } catch(Exception e) { System.out.println("Error : "+e); } System.out.println("\nThe matrix is : "); for(i=0;i<n;i++) { for(j=0;j<n;j++) System.out.print(a[i][j]+" "); System.out.print("\n"); } System.out.println("\nTransposed Matrix is : "); for(i=0;i<n;i++) { for(j=0;j<n;j++) System.out.print(b[j][i]+" "); System.out.print("\n"); } for(i=0;i<n;i++) for(j=0;j<n;j++) if(a[j][i]!=b[i][j]) break; if(i==n && j==n) System.out.println("\nMatrix is Symmetric."); else System.out.println("\nMatrix is not Symmetric."); for(i=0;i<n;i++) for(j=0;j<n;j++) { if(i==j) d1+=a[i][j]; if((i+j)==(n-1)) d2+=a[i][j]; } System.out.println("\nThe sum of first diagonal is :"+d1); System.out.println("\nThe sum of second diagonal is :"+d2); } } |
Output
Enter the size of the square matrix :
3
Enter the elements of the matrix :
1
2
3
2
2
3
3
3
3
The matrix is :
1 2 3
2 2 3
3 3 3
Transposed Matrix is :
1 2 3
2 2 3
3 3 3
Matrix is Symmetric.
The sum of first diagonal is :6
The sum of second diagonal is :8
Leave a Reply