
Source:http://en.wikipedia.org/wiki/File:SiameseMethod.gif
/*
* File Name: MagicSquare.c
* Author: MH
* Since 2013/03/10
* Toolkit: Dev C++ 4.9.9.9
*/
#include <stdio.h>
#define max_n 20
int main(){
int x[max_n][max_n];
int i, j, k, n;
do{
printf("Enter odd array size (3~19): ");
scanf("%d", &n);
}while((n>19) || (!(n%2)) || (n<3));
// fill zero into array
for (i=0; i<n; i++)
for (j=0; j<n; j++)
x[i][j] = 0;
// by placing a 1 in the middle location of top row
i = 0;
j = (n-1)/2; // find the central position
x[i][j] = 1;
for (k=2; k<=n*n; k++){
// write successive integers in an upward-right diagonal path;
i--;
j++;
// if the row and column indices all out of bound
// the next location will be at the second row
// the (n-1)th column
if ((i<0) && j>n-1){
i = 1; // second row
j = n-1; // (n-1)the column
}
// if the row index out of bound (i<0)
// use the maximum row index
else if (i<0)
i = n-1;
// if the column index out of bound (j>n-1)
// use the minimum column index
else if (j>(n-1))
j = 0;
if (x[i][j]!=0){
i += 2;
j--;
}
x[i][j] = k;
}
for (i=0; i<n; i++){
for (j=0; j<n; j++){
printf("%4d", x[i][j]);
}
printf("\n");
}
return 0;
}
沒有留言:
張貼留言