Program to check whether given Matrix is symmetric or not in C
Written by
Here, We’ll check whether the given matrix is symmetrical or not. We’ll write a program in C to find the matrix is symmetric or not.
Note: The symmetry of a matrix can only be determined when it is a square matrix.
Logic: To find whether the matrix is symmetric or not we need to compare the original matrix with its transpose.
Algorithm:
- Prompt the user for the number of rows and columns in the matrix, and use this information to create a matrix of the appropriate size.
- Iterate through the matrix and ask the user to input the values for each element.
- Once the matrix has been fully populated, create a new matrix to store the transpose. This matrix should have the same number of rows as the original matrix has columns, and the same number of columns as the original matrix has rows.
- Iterate through the original matrix and use the row and column indices to populate the transpose matrix. For example, the element in the first row and first column of the original matrix will be placed in the first column and first row of the transpose matrix.
- Compare the original matrix to the transpose matrix element by element. If all of the elements are the same, the matrix is symmetric. If any of the elements are different, the matrix is not symmetric.
- Print out a message indicating whether or not the matrix is symmetric.
Code:
#include <stdio.h>
int main() {
int A[3][3], B[3][3];
int row, col, isSym;
// Take a matrix A as input from user
printf("Enter the elements in matrix of size 3x3: \n");
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
scanf("%d", &A[row][col]);
}
}
// Finds the transpose of matrix A
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
// Stores each row of matrix A to each column of matrix B
B[row][col] = A[col][row];
}
}
// Checks whether matrix A is equal to its transpose or not
isSym = 1;
for (row = 0; row < 3 && isSym; row++) {
for (col = 0; col < 3; col++) {
if (A[row][col] != B[row][col]) {
isSym = 0;
break;
}
}
}
// If the given matrix is symmetric.
if (isSym == 1) {
printf("\n Matrix is Symmetric. \n");
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
printf("%d ", A[row][col]);
}
printf("\n");
}
} else {
printf("\n Matrix is not Symmetric.");
}
return 0;
}
Output:
Enter elements in matrix of size 3×3:
1 2 3
3 4 5
4 5 6
Matrix is not Symmetric.