Print Whether Symmetric or Not
In this final step, you will enhance the program to provide a more detailed output about matrix symmetry and create a function to improve code modularity.
Open the existing file and update the code:
cd ~/project
nano symmetric_matrix.c
Replace the previous code with the following implementation:
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
// Function to check matrix symmetry
bool is_symmetric_matrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
// Function to print matrix
void print_matrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {
printf("\nMatrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%4d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int n, matrix[MAX_SIZE][MAX_SIZE];
// Read matrix dimensions
printf("Enter the size of the square matrix: ");
scanf("%d", &n);
// Read matrix elements
printf("Enter matrix elements:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Print the entered matrix
print_matrix(matrix, n);
// Check and print symmetry status
if (is_symmetric_matrix(matrix, n)) {
printf("\nSymmetry Analysis:\n");
printf("✓ The matrix is symmetric.\n");
printf(" - All elements A[i][j] are equal to A[j][i]\n");
printf(" - Matrix is invariant under transpose\n");
} else {
printf("\nSymmetry Analysis:\n");
printf("✗ The matrix is not symmetric.\n");
printf(" - Some elements A[i][j] are not equal to A[j][i]\n");
}
return 0;
}
Compile and run the program:
gcc symmetric_matrix.c -o symmetric_matrix
./symmetric_matrix
Example output for a symmetric matrix:
Enter the size of the square matrix: 3
Enter matrix elements:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 2
Enter element [1][1]: 4
Enter element [1][2]: 5
Enter element [2][0]: 3
Enter element [2][1]: 5
Enter element [2][2]: 6
Matrix:
1 2 3
2 4 5
3 5 6
Symmetry Analysis:
✓ The matrix is symmetric.
- All elements A[i][j] are equal to A[j][i]
- Matrix is invariant under transpose
Example output for a non-symmetric matrix:
Enter the size of the square matrix: 3
Enter matrix elements:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter element [2][0]: 7
Enter element [2][1]: 8
Enter element [2][2]: 9
Matrix:
1 2 3
4 5 6
7 8 9
Symmetry Analysis:
✗ The matrix is not symmetric.
- Some elements A[i][j] are not equal to A[j][i]
Key improvements:
- Added
is_symmetric_matrix()
function for better code organization
- Created
print_matrix()
function to display matrix contents
- Enhanced output with detailed symmetry analysis
- Used visual indicators (✓/✗) to highlight symmetry status