C Program to check matrix is magic square or not

A magic square is a square matrix in which the sum of every row, every column, and both main diagonals is the same number (called the magic constant). This C program reads a square matrix and checks whether it is a magic square.

Example:

8  1  6
3  5  7
4  9  2

Every row, column and diagonal here adds up to 15, so this is a magic square (it’s the classic 3×3 “Lo Shu” square).

The Program

#include <stdio.h>

#define MAX 20

int main(void)
{
    int a[MAX][MAX], n, i, j, sum, target, magic = 1;

    printf("Enter the order of the square matrix (n) : ");
    scanf("%d", &n);

    printf("Enter the %d x %d matrix elements:\n", n, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);

    /* The magic constant is the sum of the first row. */
    target = 0;
    for (j = 0; j < n; j++)
        target += a[0][j];

    /* Check every row. */
    for (i = 0; i < n && magic; i++) {
        sum = 0;
        for (j = 0; j < n; j++)
            sum += a[i][j];
        if (sum != target) magic = 0;
    }

    /* Check every column. */
    for (j = 0; j < n && magic; j++) {
        sum = 0;
        for (i = 0; i < n; i++)
            sum += a[i][j];
        if (sum != target) magic = 0;
    }

    /* Check both diagonals. */
    if (magic) {
        int d1 = 0, d2 = 0;
        for (i = 0; i < n; i++) {
            d1 += a[i][i];
            d2 += a[i][n - 1 - i];
        }
        if (d1 != target || d2 != target) magic = 0;
    }

    if (magic)
        printf("The given matrix is a magic square.\n");
    else
        printf("The given matrix is NOT a magic square.\n");

    return 0;
}

How the Program Works

  • We take the sum of the first row as the target (magic constant) that everything else must match.
  • Three checks follow: every row sum, every column sum, and both diagonal sums must equal target.
  • The magic flag starts at 1 and is set to 0 the moment any sum doesn’t match, so we can stop early.
  • This corrected version checks both diagonals (the original only checked one) and uses a standard int main(void) instead of the old void main().

Sample Output

Enter the order of the square matrix (n) : 3
Enter the 3 x 3 matrix elements:
8 1 6
3 5 7
4 9 2
The given matrix is a magic square.

For more on 2D arrays and matrices in C, The C Programming Language by Kernighan and Ritchie is the classic reference — find it on Amazon.

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you.

Related C Programs

Try it instantly in one of the best online C compilers, or set up a local toolchain with our complete C development environment guide.

6 comments on “C Program to check matrix is magic square or not

    • Sandeepa Nadahalli says:

      Hi Shweta,

      Adding flowchart to the blog post may take a while as I am working on post by post. Please get in touch over email or Facebook and I will provide the flow chart. Also, I will be happy to explain how this program works.

      Happy coding!

      Reply
  • I am SAP ABAP developer looking for magic square matrix. Search engine landed me to your page.

    Having done some C during college days, I was able to understand. I could apply the concept in ABAP language and get my magic square in ABAP. 🙂

    Thanks for this post.

    Raju

    Reply
    • Sandeepa Nadahalli says:

      Hi Raju,

      I’m very happy this blog post helped you.

      Thanks for your comment. That encourages me to write more.

      Happy coding!

      Cheers,
      Sandeepa

      Reply
  • Hishe Hintsa Fisseha says:

    Dear Sandeepa,

    Just wanted to suggest a little modification on your program.

    In its present form, your code does not check if the sums of the rows(sum1) are equal to sum. Eg. try this one

    2 6 3
    5 4 3
    6 3 7

    or

    4 8 8
    7 5 1
    4 2 6

    Your program will tell that these matrices are magic matrices, Even though the fact is that they aren’t b/c the sums of the rows is different.

    Reason for why this is happening: You used the variable flag to check for the sums of the rows and then again to check for the sums of the column. By doing so you are overwriting the former value of flag by the latter.

    Suggested Solution1: use two different flags for the two loops(may be flag1 and flag2) and check if both of them are equal to 1.

    Suggested Solution2: use print result and return instead of break inside the two for loops. (I would prefer this one).

    Thank you!!!

    PS: \n and \t are written as n and t. I hope you can edit them as well.

    Reply
    • Sandeepa Nadahalli says:

      Hello Hishe Hintsa Fisseha,

      Thank you very much for your comment. I appreciate you spending time to write such detailed feedback.

      I have modified the program now. Do check when you get time.

      I have lost some \n s when I moved my blog from blogger to WordPress!

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>