C program to check symmetric matrix

Write a C program to read elements in a matrix and check whether the given matrix is symmetric matrix or not. How to check symmetric matrix in C.

Example: If elements of the matrix is:
1 2 3
2 4 5
3 5 8

Output: Given matrix is symmetric matrix.

Required knowledge:

Basic C programming, For loop, Array, Matrix
Before checking whether a matrix is symmetric or not you must know how to find transpose of a matrix in C.

Symmetric Matrix:

Symmetric matrix is a square matrix which is equal to its transpose. All symmetric matrix must be a square matrix.

A symmetric matrix A is defined as: A = AT
Symmetric matrix

Algorithm to check symmetric matrix:

To check whether a matrix A is symmetric or not we need to check whether A = AT or not.

Step 1: Read elements in matrix A.
Step 2: Find transpose of matrix A.
Step 3: If matrix A is equal to its transpose AT then it is symmetric matrix.
If Aij = ATij (Where 1 ≤ i ≤ m and 1 ≤ j ≤ n) then the matrix is symmetric.

Program:

/**
 * C program to check whether a matrix is symmetric matrix or not
 */

#include <stdio.h>

int main()
{
    int A[3][3], B[3][3];
    int row, col, isSymmetric;

    /*
     * Reads elements in matrix A from user
     */
    printf("Enter 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
     */
    isSymmetric = 1;
    for(row=0; row<3 && isSymmetric; row++)
    {
        for(col=0; col<3; col++)
        {
            /* If matrix A is not equal to its transpose */
            if(A[row][col] != B[row][col])
            {
                isSymmetric = 0;
                break;
            }
        }
    }

    /*
     * If the given matrix is symmetric.
     */
    if(isSymmetric==1)
    {
        printf("\nThe given matrix is Symmetric matrix: \n");

        for(row=0; row<3; row++)
        {
            for(col=0; col<3; col++)
            {
                printf("%d ", A[row][col]);
            }

            printf("\n");
        }
    }
    else
    {
        printf("\nThe given matrix is not Symmetric matrix.");
    }

    return 0;
} 
Output
Enter elements in matrix of size 3x3:
1 2 3
2 4 5
3 5 8

The given matrix is Symmetric matrix:
1 2 3
2 4 5
3 5 8

Happy coding ;)


You may also like

Labels: , , ,