Tuesday, January 17, 2012

Magic Square


Logic 
Assign the numbers in the order 1,2,3... in the matrix in the following pattern.
Put the first number (1) as the middle element in the first row (Let it be i,j). 

Put the next element in the diagonally previous (i-1,j-1) location, if the location is empty.

The rows and columns are considered to be circular, i.e. if i-1 or j-1 comes to a negative value, then highest row or column is taken.

If the location is not empty then put the number in the next row, in the same column(i+1,j), here , rows are considered to be circular.

Continue assigning numbers in this pattern until the matrix is filled (ie n * n times ) */

#include
#define N 10 //Defines the maximum size of the matrix

void main( )
{
int a[N][N]={{0}},i,j,k,n,s,p; //Declaring and initialising the variables

label:
clrscr( );
printf("Enter the size : "); //Reading the size
scanf("%d",&n);
if((n%2==0)||(n>N)) //Validating the input size
{
printf("\n\nThe size must be even and less than %d :Try again\n\n",N);
printf("Press any key to continue ........\n");
getch();
goto label;
}
j=0;
k=n/2;

//Generating the Magic square
for(i=1;i<=n*n;i++)
{
a[j][k]=i;
s=j-1;
p=k-1;
if(s<0)
s=n-1;
if(p<0)
p=n-1;
if(a[s][p]!=0)
j++;
else
{
j=s;
k=p;
}
}

printf("\nThe Magic square is \n\n");
for(i=0;i
{
for(j=0;j
printf(" %2d ",a[i][j]);
printf("\n");
}
getch( );
}

0 comments:

Flag counter

free counters