-
Notifications
You must be signed in to change notification settings - Fork 765
/
Copy pathMagicSquare.c
72 lines (58 loc) · 850 Bytes
/
MagicSquare.c
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
66
67
68
69
70
71
72
#include<stdio.h>
#include<string.h>
// program to generate a magic square for a odd given input
main()
{
int n,i,j,r,c;
printf("Enter the size of magic square: \n");
scanf("%d",&n);
int a[n][n];
memset(a,0,sizeof(a));
if(n%2!=0)
{
r=n/2;
c=n-1;
for(i=1;i<=n*n;i++)
{
if(r==-1 && c==n)
{
r=0;
c=n-2;
}
else if(r==-1)
{
r=n-1;
}
else if(c==n)
{
c=0;
}
if(a[r][c])
{
r=(r+1)%n;
c=c-2;
if(c==-1)
c=n-1;
else if (c==-2)
c=1;
a[r][c]=i;
r--;
c++;
}
else
{
a[r][c]=i;
r--;
c++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%5d",a[i][j]);
printf("\n");
}
}
else
printf("Enter the odd size for magic square \n");
}