Question

• 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.
```
```

Share code with your friends

Code

```				```
import java.util.Scanner;
public class SymmetricMatrix
{
public static void main(String args[])
{
int m=0,i=0,j=0,leftDiagonalSum=0,rightDiagonalSum=0;
boolean flag = true;
int arr[][];
Scanner sc=new Scanner(System.in);
System.out.print("Matrix size: ");
m = sc.nextInt();
if(m <= 2 || m >= 10)
{
System.out.println("Size out of range!");

}
else
{
arr = new int[m][m];
System.out.println("Enter matrix elements:");
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
arr[i][j] = sc.nextInt();
if(i == j)
{
leftDiagonalSum += arr[i][j];
}
if(i + j == m - 1)
{
rightDiagonalSum += arr[i][j];
}
}
}

System.out.println("Original Matrix:");
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
System.out.print(arr[i][j] + "\t");
if(arr[i][j] != arr[j][i])
{
flag = false;
}
}
System.out.println();
}

if(flag==true)
{
System.out.println("The matrix is symmetric.");
}
else
{
System.out.println("The matrix is not symmetric.");
}
System.out.println("Sum of left diagonal elements: " + leftDiagonalSum);
System.out.println("Sum of right diagonal elements: " + rightDiagonalSum);
}
}
}

```
```

Sale

50
Sale

150
Sale

200
Sale

50
Sale

50
Sale

50
Sale

50
Sale

50
Sale

50