Check If a Matrix is Symmetric in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a matrix is symmetric in C programming. The lab covers the following steps: reading the dimensions and elements of the matrix, checking if the matrix is symmetric by comparing the elements at symmetric positions, and printing whether the matrix is symmetric or not. The lab provides a step-by-step guide with code examples to help you understand the process of checking matrix symmetry in C.

The lab starts by showing how to read the dimensions and elements of the matrix using C programming. It then introduces the logic to check if the matrix is symmetric by comparing the elements at symmetric positions. Finally, the lab demonstrates how to print the result, indicating whether the matrix is symmetric or not.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/output -.-> lab-435140{{"`Check If a Matrix is Symmetric in C`"}} c/if_else -.-> lab-435140{{"`Check If a Matrix is Symmetric in C`"}} c/for_loop -.-> lab-435140{{"`Check If a Matrix is Symmetric in C`"}} c/arrays -.-> lab-435140{{"`Check If a Matrix is Symmetric in C`"}} c/user_input -.-> lab-435140{{"`Check If a Matrix is Symmetric in C`"}} end

Read Dimensions and Elements

In this step, you will learn how to read matrix dimensions and elements in C programming for checking matrix symmetry. We'll create a program that allows users to input the size and elements of a matrix.

First, let's create a new C file for our matrix symmetry program:

cd ~/project
nano symmetric_matrix.c

Now, add the following code to read matrix dimensions and elements:

#include <stdio.h>

#define MAX_SIZE 100

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
    printf("\nEntered Matrix:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Compile and run the program:

gcc symmetric_matrix.c -o symmetric_matrix
./symmetric_matrix

Example output:

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

Entered Matrix:
1 2 3
2 4 5
3 5 6

Let's break down the key parts of the code:

  • #define MAX_SIZE 100 sets a maximum matrix size to prevent buffer overflows
  • scanf() is used to read matrix dimensions and individual elements
  • Nested loops are used to input and display matrix elements
  • The program ensures the user can input a square matrix of any size up to 100x100

Check if A[i][j] = A[j][i]

In this step, you will modify the previous program to check if the matrix is symmetric by comparing elements across rows and columns.

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

int main() {
    int n, matrix[MAX_SIZE][MAX_SIZE];
    bool is_symmetric = true;

    // 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]);
        }
    }

    // Check symmetry
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (matrix[i][j] != matrix[j][i]) {
                is_symmetric = false;
                break;
            }
        }
        if (!is_symmetric) break;
    }

    // Print symmetry result
    if (is_symmetric) {
        printf("\nThe matrix is symmetric.\n");
    } else {
        printf("\nThe matrix is not symmetric.\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

The matrix is symmetric.

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

The matrix is not symmetric.

Key points in the code:

  • is_symmetric boolean variable tracks matrix symmetry
  • Nested loops compare matrix[i][j] with matrix[j][i]
  • If any elements differ, is_symmetric is set to false
  • The program breaks out of loops early if asymmetry is found

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

Summary

In this lab, you will learn how to read the dimensions and elements of a matrix in C programming, and then check if the matrix is symmetric. First, you will create a program that allows users to input the size and elements of a matrix. Then, you will modify the program to check if the matrix is symmetric by verifying that each element A[i][j] is equal to its corresponding element A[j][i]. Finally, you will print whether the matrix is symmetric or not.

The key learning points from the completed steps include reading matrix dimensions and elements using scanf(), displaying the entered matrix, and comparing matrix elements to determine symmetry. The program ensures the user can input a square matrix of any size up to 100x100.

Other C Tutorials you may like