Function Assignment 25 — Check If a Matrix Is Symmetric Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check If a Matrix Is Symmetric Using a Function

šŸ“‘ On this page:
  • What makes a matrix symmetric
  • Designing the isSymmetric function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
šŸ“š In this program, you will learn:
  • What it means for a matrix to be symmetric
  • Why only square matrices can be symmetric
  • Why checking only the upper triangle is sufficient
  • How early returns make the check efficient
  • How symmetry arises in real applications (dot products, covariance, adjacency matrices)

What makes a matrix symmetric

A matrix is symmetric if it equals its own transpose: A = AT. Concretely, this means A[i][j] = A[j][i] for every pair of indices i and j. The entry in row 2, column 5 is the same as the entry in row 5, column 2 — and this is true for every off-diagonal pair. The values mirror across the main diagonal.

Only square matrices can be symmetric, because if A is m Ɨ n and m ≠ n, then A and AT have different shapes — one is m Ɨ n, the other is n Ɨ m — and you can't say they're equal. So the first prerequisite for symmetry is that the matrix be square. Our function assumes this and doesn't check it (it can't, since the shape is baked into the type). If you wanted a runtime check for a rectangular matrix passed as a 1D array, you'd have to compare m and n yourself and refuse to check symmetry if they differ.

Why does symmetry matter? Symmetric matrices appear everywhere. The Gram matrix ATA (used in least-squares regression) is always symmetric. The covariance matrix in statistics is symmetric. The adjacency matrix of an undirected graph is symmetric. The Hessian matrix of a twice-differentiable function is symmetric (Schwarz's theorem). In physics, inertia tensors and stress tensors are symmetric. In machine learning, attention matrices and distance matrices are symmetric. Symmetric matrices have special properties — real eigenvalues, orthogonal eigenvectors, efficient factorization algorithms (Cholesky decomposition) — that make them especially useful. Checking whether a matrix is symmetric is a basic diagnostic step in all of these contexts.

The check itself is trivial: compare A[i][j] with A[j][i] for each pair. If any pair doesn't match, the matrix isn't symmetric. If all pairs match, it is. The only subtlety is that you don't need to check the diagonal — A[i][i] is trivially equal to itself, and there's no comparison to make. And you don't need to check both (i, j) and (j, i) — checking one is enough, since the other is the same comparison reversed.

šŸ’” In one line: for each pair (i, j) with i < j, check that A[i][j] == A[j][i]. If any pair fails, return 0. If all pairs pass, return 1.

A symmetric matrix with the main diagonal highlighted and arrows showing that upper and lower triangles mirror each other.

Designing the isSymmetric function

The signature is simple — just the matrix and a return value:

Part Choice Why
Function nameisSymmetricReads naturally: if (isSymmetric(A)). Same "is" convention as isPrime, isEven, isLeapYear.
Parameterconst int a[N][N]Read-only. Square dimension N must be a compile-time constant.
Return typeint1 for symmetric, 0 otherwise. The C convention for boolean-returning functions.

The prototype:

#define N 3

int isSymmetric(const int a[N][N]);
                                

And the definition — the entire function is a nested loop with an early return:

int isSymmetric(const int a[N][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
            if (a[i][j] != a[j][i]) {
                return 0;
            }
        }
    }
    return 1;
}
                                

Six lines of logic. The outer loop iterates over rows, the inner over columns to the right of the diagonal (starting at i + 1). For each pair, check equality. If any pair fails, return 0 immediately — no need to continue. If the whole loop completes without a mismatch, return 1.

The inner loop starting at i + 1 is the key optimization. It skips:

  • The diagonal (j == i): a[i][i] always equals itself, so there's nothing to check.
  • The lower triangle (j < i): those pairs are already covered by their mirrored positions in the upper triangle. Checking a[2][1] == a[1][2] is the same as checking a[1][2] == a[2][1] — redundant.

So the function does only n(n-1)/2 comparisons — exactly half of what a full nested loop would do. For an nƗn matrix, that's the minimum number of off-diagonal pairs to check. The efficiency is optimal.

An alternative implementation that returns the result via a single boolean variable, avoiding the early return:

int isSymmetricAlt(const int a[N][N]) {
    int symmetric = 1;
    for (int i = 0; i < N && symmetric; i++) {
        for (int j = i + 1; j < N && symmetric; j++) {
            if (a[i][j] != a[j][i]) {
                symmetric = 0;
            }
        }
    }
    return symmetric;
}
                                

This version avoids the early return by using a flag and including it in both loop conditions. The && symmetric in both loops means the loops exit as soon as a mismatch is found. Functionally identical to the early-return version. Some programmers prefer this style; others find it more awkward. Either is correct; pick whichever reads better to you.

And a version that also checks whether the matrix is square — useful when you're dealing with matrices passed as a flat array and both dimensions are runtime values:

int isSymmetricDynamic(int rows, int cols, const int a[rows][cols]) {
    if (rows != cols) return 0;
    for (int i = 0; i < rows; i++) {
        for (int j = i + 1; j < cols; j++) {
            if (a[i][j] != a[j][i]) return 0;
        }
    }
    return 1;
}
                                

This version uses C99 VLAs to accept any matrix shape, checks that it's square, and then does the symmetry test. It's more general but requires C99 VLAs (which not every compiler supports in older codebases). For the fixed-size case, the simpler version is cleaner.

šŸŽÆ Key idea: symmetry is about the upper and lower triangles mirroring each other. You only need to check one side — the other is guaranteed by definition. The inner loop starting at i + 1 is the code realization of this.

Complete C Program

Program: read a square matrix, check if it's symmetric

#include <stdio.h>

#define N 3

/* Function prototype */
int isSymmetric(const int a[N][N]);

int main(void) {
    int A[N][N];

    printf("Enter matrix A (%d rows, %d columns):\n", N, N);
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (scanf("%d", &A[i][j]) != 1) return 1;
        }
    }

    /* Print the matrix for reference */
    printf("\nMatrix A:\n");
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%4d", A[i][j]);
        }
        printf("\n");
    }

    if (isSymmetric(A)) {
        printf("\nThe matrix is symmetric.\n");
    } else {
        printf("\nThe matrix is NOT symmetric.\n");
    }

    return 0;
}

/* Symmetry check — upper triangle vs. lower triangle */
int isSymmetric(const int a[N][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
            if (a[i][j] != a[j][i]) {
                return 0;
            }
        }
    }
    return 1;
}
                                    

And a version that identifies exactly where the mismatch is, for debugging or diagnostic output:

Variant: report the first mismatch

#include <stdio.h>
#define N 3

int checkSymmetryWithDetail(const int a[N][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
            if (a[i][j] != a[j][i]) {
                printf("Mismatch at (%d,%d) vs (%d,%d): %d != %d\n",
                       i, j, j, i, a[i][j], a[j][i]);
                return 0;
            }
        }
    }
    return 1;
}

int main(void) {
    int A[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    if (checkSymmetryWithDetail(A)) {
        printf("Symmetric.\n");
    } else {
        printf("Not symmetric.\n");
    }
    return 0;
}
                                    

This version prints the exact coordinates of the first mismatch — helpful when you're debugging a matrix that "should" be symmetric but isn't. The output tells you which pair of cells disagreed, so you can trace back to the data or the code that produced them.

And a version that uses the alternative flag-based approach — no early return, but exits the loops as soon as a mismatch is found:

Variant: flag-based, no early return

#include <stdio.h>
#define N 4

int isSymmetric(const int a[N][N]) {
    int ok = 1;
    for (int i = 0; i < N && ok; i++) {
        for (int j = i + 1; j < N && ok; j++) {
            if (a[i][j] != a[j][i]) ok = 0;
        }
    }
    return ok;
}

int main(void) {
    int A[N][N] = {
        {1, 2, 3, 4},
        {2, 5, 6, 7},
        {3, 6, 8, 9},
        {4, 7, 9, 0}
    };
    printf("Symmetric: %s\n", isSymmetric(A) ? "yes" : "no");
    return 0;
}
                                    

The flag-based version is arguably cleaner because it has only one exit point (the final return ok). Early returns are also fine, but some coding standards prefer a single exit for readability. Both work; pick the style that fits your codebase.

Program Output

A symmetric matrix:

Enter matrix A (3 rows, 3 columns):
1 2 3
2 5 6
3 6 9

Matrix A:
   1   2   3
   2   5   6
   3   6   9

The matrix is symmetric.
                                

Notice the structure: A[0][1]=2 equals A[1][0]=2. A[0][2]=3 equals A[2][0]=3. A[1][2]=6 equals A[2][1]=6. The upper triangle mirrors the lower triangle. That's the symmetry.

A non-symmetric matrix:

Enter matrix A (3 rows, 3 columns):
1 2 3
4 5 6
7 8 9

Matrix A:
   1   2   3
   4   5   6
   7   8   9

The matrix is NOT symmetric.
                                

Here A[0][1]=2 but A[1][0]=4 — mismatch. The function returns 0 at the first comparison. The rest of the matrix doesn't even matter; a single mismatch is enough to disprove symmetry.

An identity matrix:

Enter matrix A (3 rows, 3 columns):
1 0 0
0 1 0
0 0 1

The matrix is symmetric.
                                

The identity matrix is trivially symmetric: every off-diagonal cell is 0, and the diagonal is 1. It's the most symmetric matrix possible.

A zero matrix:

Enter matrix A (3 rows, 3 columns):
0 0 0
0 0 0
0 0 0

The matrix is symmetric.
                                

The zero matrix is also trivially symmetric (every cell is 0). Both identity and zero matrices are symmetric — a useful sanity check for any symmetry code.

And the diagnostic variant on a non-symmetric matrix:

Mismatch at (0,1) vs (1,0): 2 != 4
Not symmetric.
                                

The diagnostic output pinpoints the mismatch: cell (0,1) has value 2, cell (1,0) has value 4. Once you know which pair disagrees, you can inspect the matrix structure or the code that produced it. This is a simple but effective debugging aid.

Step-by-Step Explanation

Let's walk through the algorithm and look at the design choices.

1. The inner loop starts at i + 1

This is the key optimization. The inner loop only examines cells above the diagonal (where j > i). The diagonal itself (j == i) is skipped because a[i][i] is trivially equal to itself. The lower triangle (j < i) is skipped because those cells are the mirrors of upper-triangle cells that we're already checking. So the function does exactly n(n-1)/2 comparisons — the minimum number needed to verify symmetry.

2. The early return

if (a[i][j] != a[j][i]) return 0; — as soon as a single mismatch is found, the function returns 0 immediately. There's no need to continue checking; one counterexample is enough to disprove symmetry. This is a big win for non-symmetric matrices where the mismatch happens early — the function can return in O(1) comparisons instead of O(n²).

3. Tracing isSymmetric on {{1,2,3},{2,5,6},{3,6,9}}

  1. i=0, j=1: a[0][1] = 2, a[1][0] = 2. Match. Continue.
  2. i=0, j=2: a[0][2] = 3, a[2][0] = 3. Match. Continue.
  3. i=1, j=2: a[1][2] = 6, a[2][1] = 6. Match. Continue.
  4. i=2: inner loop doesn't run (j starts at 3, which is ≥ N=3).
  5. Loop ends. Return 1. āœ“

Three comparisons total (n(n-1)/2 = 3*2/2 = 3). For a full check, you'd need 9 comparisons (every cell vs. every cell, minus the trivial ones). The upper-triangle approach halves the work.

4. Tracing isSymmetric on {{1,2,3},{4,5,6},{7,8,9}}

  1. i=0, j=1: a[0][1] = 2, a[1][0] = 4. Mismatch! Return 0.

One comparison — the function returns immediately. This is the best case for a non-symmetric matrix: fail on the first check. For a matrix with only one bad pair buried deep, the function would do more comparisons, but never more than n(n-1)/2.

5. Why square matrices only

Symmetry requires A = AT, which requires A and AT to be the same shape. That requires the matrix to be square. For a rectangular matrix, "AT" is a different shape, so "equals" is meaningless. Our function assumes a square matrix (the type int a[N][N] enforces it). If you were writing a generic checker, you'd first verify that the dimensions match.

6. Symmetry is about the matrix, not the type

The property "symmetric" is a mathematical fact about the values in the matrix, not a compile-time property. Two matrices of the same size can have the same type but different symmetry: one is symmetric, the other isn't. That's why the check is a runtime function, not a type constraint. You can't know at compile time whether a given matrix's values satisfy A[i][j] == A[j][i] — you have to check the data.

7. Complexity

Worst case: O(n²) time — the entire upper triangle is checked. Best case: O(1) — a mismatch on the first comparison. Average case: O(n²) for a symmetric matrix (all checks pass) or O(1) to O(n²) for a non-symmetric one, depending on where the first mismatch is. Space: O(1) beyond the matrix itself. All optimal for this problem — you can't verify symmetry with fewer than n(n-1)/2 comparisons in the worst case.

8. Numerical precision

For integer matrices, the equality comparison is exact. For floating-point matrices, you'd use a tolerance: if (fabs(a[i][j] - a[j][i]) > EPSILON) instead of ==. This is because floating-point arithmetic introduces rounding, so two cells that "should" be equal might differ in the last few bits. Choosing an appropriate epsilon depends on the application — for scientific data, something like 1e-9 is typical. For our integer example, no tolerance is needed.

9. Alternative: transposing and comparing

You could also check symmetry by computing the transpose of A and then comparing A to the transpose element by element. That's the approach from assignment 24, extended with an extra comparison. It uses O(n²) extra memory (for the transpose) and does the same number of comparisons. So it's strictly worse than the direct check — the direct check is the same computation without the unnecessary copy. This is a good lesson: sometimes the "mathematically clean" formulation is more expensive than a direct check, and you should reach for the direct check.

10. Related properties

Symmetry has several variants worth knowing:

  • Skew-symmetric: AT = -A, so A[i][j] = -A[j][i]. The diagonal must be 0 (since A[i][i] = -A[i][i] implies 0).
  • Hermitian: for complex matrices, AH = A where AH is the conjugate transpose. The real analog is symmetric.
  • Persymmetric: symmetric about the anti-diagonal instead of the main diagonal.
  • Centrosymmetric: symmetric under 180° rotation.

Each of these has its own check, but they all follow the same pattern: compare A[i][j] with some transformed version of A[j][i]. The specific transformation is the only difference.

šŸ” Try this: modify the function to check skew-symmetry: A[i][j] == -A[j][i] for all i, j, and A[i][i] == 0 for all i. The diagonal check is essential — without it, the function would accept matrices that are "almost" skew-symmetric but have nonzero diagonal. Then test with a known skew-symmetric matrix like {{0, 1, -2}, {-1, 0, 3}, {2, -3, 0}}.

Frequently Asked Questions

1. Can a non-square matrix be symmetric?

No. Symmetry requires A = AT, and A and AT can only be equal if they have the same dimensions. A 3Ɨ2 matrix's transpose is 2Ɨ3, so they're different shapes and can't be equal. Our function assumes a square matrix, which the type int a[N][N] enforces. If you wanted a runtime check for arbitrary matrices, you'd first verify that rows == columns before checking symmetry.

2. Why only check the upper triangle?

Because the lower triangle is the mirror of the upper triangle. If A[i][j] == A[j][i] for all j > i, then by definition A[j][i] == A[i][j] for all i > j — those are the same comparison, just viewed from the other side. Checking both would be redundant. The upper-triangle-only check does n(n-1)/2 comparisons instead of n², which is exactly half the work.

3. Why does the function return 0 as soon as it finds a mismatch?

Because one mismatch is enough to disprove symmetry. If A[0][1] != A[1][0], the matrix isn't symmetric — checking the other cells won't change that fact. Returning 0 immediately is both correct and efficient. For a non-symmetric matrix where the mismatch is early, this makes the function run in O(1) time instead of O(n²).

4. How do I check if a matrix is symmetric for floating-point values?

Use an epsilon tolerance instead of exact equality: if (fabs(a[i][j] - a[j][i]) > EPS) where EPS is something like 1e-9. This handles the case where two values that "should" be equal differ in their last bits due to floating-point rounding. The choice of EPS depends on the application — for scientific data, 1e-9 is common; for financial data, you might use something larger. Without a tolerance, exact equality might fail even for numerically symmetric matrices.

5. What are some examples of symmetric matrices in real life?

Many real-world matrices are symmetric. The covariance matrix in statistics is always symmetric (cov(X,Y) = cov(Y,X)). The adjacency matrix of an undirected graph is symmetric (an edge from A to B implies an edge from B to A). The Gram matrix ATA in linear regression is symmetric. The inertia tensor in physics is symmetric. The distance matrix between cities is symmetric (distance from A to B equals distance from B to A). In machine learning, the Hessian of the loss function is symmetric, which is why quasi-Newton methods like BFGS work. Symmetric matrices are, in a sense, "the default" in many applications.

6. What's a skew-symmetric matrix?

A matrix where AT = -A, or equivalently A[i][j] = -A[j][i] for all i, j. The diagonal must be 0 (since A[i][i] = -A[i][i] implies 2*A[i][i] = 0). Skew-symmetric matrices appear in physics (angular velocity, electromagnetic field tensors) and are related to rotations. The check is the same as symmetric, just with a sign flip: A[i][j] == -A[j][i], plus a check that the diagonal is all zeros.

šŸ’” Tip: Once this works, try the skew-symmetric check — it's a one-character change to the comparison, plus a check that the diagonal is zero. Then try a "diagonally dominant" check: |A[i][i]| > sum of |A[i][j]| for j != i for all i. Diagonal dominance is a common sufficient condition for iterative solvers to converge, so it shows up in numerical linear algebra. Each variant is a small twist on the same template — nested loops, one comparison per cell, early return on failure.

šŸ“– Related Tutorials

  • Introduction to Functions in C
  • Two Dimensional Arrays
  • Passing Arrays to Functions
  • Function Definition
  • Function Declaration
  • Previous: Calculate the Transpose of a Matrix
  • Next: Perform Matrix Multiplication Using a Function
  • All 33 Function Assignments

Previous Topic: -->> 24. Calculate the Transpose of a Matrix Using a Function   ||   Next Topic: -->> 26. Perform Matrix Multiplication Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.