/*
Magic Square:-
It is a square matrix whose row element's addition and column element's
addition and diagonal element's addition is same.
Read more about Magic Square:- http://en.wikipedia.org/wiki/Magic_square
*/
#include<stdio.h>
#define MAX 100
int main()
{
int sqr[MAX][MAX];
int i,j,p,q,n;
int cnt=1;
label:
printf("\nEnter matrix size:");
scanf("%d",&n);
if(n%2==0)
{
printf("\nPlease enter odd number.");
goto label;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
sqr[i][j]=0;
i=p=q=0;
j=(n-1)/2;
sqr[i][j]=cnt++;
do
{
if(i==0)
p=n-1;
else
p=i-1;
if(j==0)
q=n-1;
else
q=j-1;
if(sqr[p][q])
{
p=i+1;
q=j;
sqr[p][q]=cnt++;
}
if(sqr[p][q] == 0)
sqr[p][q]=cnt++;
i=p;
j=q;
}while(cnt != (n*n)+1);
printf("\nMagic Square is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("\t%d",sqr[i][j]);
printf("\n");
}
return 0;
}
WHAT'S NEW?
Loading...
0 comments:
Post a Comment