This paper illustrates the method of realizing the odd-order magic square in C language. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
#include "stdio.h"
#include "string.h"
#include "Stdlib.h"
#define N 5
void Main () {
int a[n][n]={0};
int i,j;
int k;
i = 0;
j = N/2;
A[0][j]=1;
for (k = 2; k <= n*n; k++) {
if (i = = 0 && J = = N-1) {//First, determine whether the first number is the top-right number, if the latter number directly below the previous number
i=i+1;
A[I][J] = k;
Continue
}
i = (i-1+n)%n;//computes the coordinates of the top right corner of the previous number
j = (j+1)%N;
if (A[i][j]!= 0) {//If there is an element in the upper-right corner of the previous number, the latter number is filled directly below the previous number
i = ((i+1)%n+1)%n;//Restore coordinates
j = (j-1+n)%N;
A[I][J] = k;
}else{//above conditions are not satisfied, the last number placed in the upper right corner of the previous number
A[I][J] = k;
}
}
for (i = 0; i < N; i++) {
for (j = 0; J < N; J + +) {
printf ("M", A[i][j]);
}
printf ("\ n");
}
}
The test data are as follows:
N = 3
8 1 6
3 5 7
4 9 2
I hope this article will help you with the C language program.