C language to achieve odd order magic square method

  • 2020-04-02 02:57:37
  • OfStack

This paper illustrates the method of realizing odd order magic square in C language. Share with you for your reference. The specific implementation method is 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 previous number is the most upper right hand corner of the number, if the latter number directly filled in below the previous number
i=i+1;
a[i][j] = k;
continue;
}
i = (i-1+N)%N;//Calculate the coordinate
in the upper 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 directly below the previous number
i = ((i+1)%N+1)%N;//Restore coordinates
j = (j-1+N)%N;
a[i][j] = k;
}else{//The above conditions are not satisfied, the latter number is 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 September 2

Hope that the article described in the C programming language for you to help.


Related articles: