Symmetric Matrix Java Program ISC Computer Science 2025 Practical

Write a program to declare a square matrix A[][] of order M × M 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 said to be symmetric or not. A square matrix is said to be symmetric, if the element of 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.

Example 1
INPUT:
M = 3
Enter elements of the matrix:
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
Enter elements of the matrix:
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: SIZE IS OUT OF RANGE.

import java.util.Scanner;
class Symmetric{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("M = ");
        int m = Integer.parseInt(in.nextLine());
        if(m < 3 || m > 9){
            System.out.println("SIZE IS OUT OF RANGE");
            return;
        }
        int a[][] = new int[m][m];
        System.out.println("Enter elements of the matrix:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                a[i][j] = Integer.parseInt(in.nextLine());
            }
        }
        int left = 0;
        int right = 0;
        boolean isSymmetric = true;
        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])
                    isSymmetric = false;
                if(i == j)
                    left += a[i][j];
                if(i + j == m - 1)
                    right += a[i][j];
            }
            System.out.println();
        }
        if(isSymmetric)
            System.out.println("THE GIVEN MATRIX IS SYMMETRIC.");
        else
            System.out.println("THE GIVEN MATRIX IS NOT SYMMETRIC.");
        System.out.println("THE SUM OF THE LEFT DIAGONAL = " + left);
        System.out.println("THE SUM OF THE RIGHT DIAGONAL = " + right);
    }
}