Magic Squarue Program in C

#include <stdio.h>
#include <bios.h>
#include <dos.h>
#include <stdlib.h>

#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<n;i++)
{
for(j=0;j<n;j++)
printf(" %2d ",a[i][j]);
printf("\n");
}
getch( );
}

Comments

Post a Comment

Popular Posts