Magic Square Description:

  • A magic square is an N*N matrix;
  • The sum of each row, each column, and the diagonals of this matrix are all equal;

Magic square example:

3rd-order magic square:

8   1   6

3   5   7

4   9   2

Sum of each row:

8+1+6=15;

3+5+7=15;

4+9+2=15;

Sum of each column:

8+3+4=15;

1+5+9=15;

6+7+2=15;

Sum of diagonals:

8+5+2=15;

6+5+4=15;

Magic square calculation rules (rows and columns start at 1):

1. Place "1" in the first row, middle column;

2. Starting from 2 to N*N, each number follows this rule: the row where each number is stored is the previous number's row minus 1; the column where each number is stored is the previous number's column plus 1;

3. When a number's row is 1, the next number's row is N;

4. When a number's column is N, the next number's column is 1, and the row number decreases by 1;

5. If the position determined by the above rules already has a number, or the previous number is at the 1st row and Nth column,

the next number is placed directly below the previous number (i.e., row number decreases by 1, column unchanged);

Source Code

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define N 5

int main()
{
    int a[N][N] = {0};
    int count = 1;
    int row = 0, cul = N / 2;
    while (count <= N*N)
    {
        a[row][cul] = count;
        int i = row;
        int j = cul;
        if (i == 0)
        {
            i = N - 1;
        }
        else
        {
            i = i - 1;
        }
        j = (j + 1) % N;
        if (a[i][j]!=0||(row==0&&cul==N-1))
        {
            i = row + 1;
            j = cul;
        }
        row = i;
        cul = j;
        count++;
    }

    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("%3d",a[i][j]);
        }
        printf("\n");
    }

    system("pause");
}

The output of the above code is:

17 24  1  8 15
23  5  7 14 16
 4  6 13 20 22
10 12 19 21  3
11 18 25  2  9