summaryrefslogtreecommitdiff
path: root/algorithms/magic.c
blob: 31e50ea6a2feb6b5ce388e52a0132d021c2d0ac6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>


/*
  1...25

  0 0 1 0 0
  0 0 0 0 0
  0 0 0 0 0
  0 0 0 0 0
  0 0 0 0 0
*/
void
magic(unsigned int n)
{
  int a[n][n];
  unsigned int i, j;

  for(i=0; i<n; i+=1) {
    for(j=0; j<n; j+=1) {
      a[i][j] = 0;
    }
  }

  int k;
  int row = n - 1;
  int col = n / 2;
  for (k = 1; k <= n * n; ++k) {
    a[row][col] = k;
    if (k % n == 0) {
      --row;
      if (row < 0)
        row = n - 1;
    } else {
      ++row;
      if (row == n)
        row = 0;
      ++col;
      if (col == n)
        col = 0;
    }
  }

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

int main(void)
{
  int n = 3;

  if(n%2==0) {
    printf("n has to be odd\n");
    exit(1);
  }

  magic(n);

  return 0;
}