Program opened below. You can scroll through the algorithm, Java code and output.

Symmetric Matrix and Diagonal Sums

Download .java

Question

Accept a square integer matrix of order M where 3 < M < 10. Display the matrix, determine whether it is symmetric (A[i][j] = A[j][i]) and calculate the sums of the left and right diagonals.

Step 1: Start. Step 2: Declare the variables and data structures required for the task. Step 3: Start and input M. Step 4: If M <= 2 or M >= 10, display SIZE IS OUT OF RANGE and stop. Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution. Step 6: Input all M*M integer elements. Step 7: Display the original matrix. Step 8: Assume the matrix is symmetric. Step 9: Compare A[i][j] with A[j][i] for every pair; if any differ, mark it not symmetric. Step 10: Add A[i][i] to the left diagonal sum. Step 11: Add A[i][M-1-i] to the right diagonal sum. Step 12: Display symmetry result and both sums. Step 13: Stop.
Java
import java.util.*;
class SymmetricMatrix {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        if (m <= 2 || m >= 10) {
            System.out.println("SIZE IS OUT OF RANGE");
            return;
        }
    int[][] a = new int[m][m];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < m; j++) {
            a[i][j] = sc.nextInt();
        }
}
boolean symmetric = true;
int left = 0, right = 0;
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] + " ");
        if (a[i][j] != a[j][i]) {
            symmetric = false;
        }
}
System.out.println();
left += a[i][i];
right += a[i][m - 1 - i];
}
System.out.println(symmetric ? "THE GIVEN MATRIX IS SYMMETRIC" : "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);
}
}
Input: 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
← Previous Program 64 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.