Tuesday, 10 January 2012

Magic Square

#include <stdio.h>
#include<stdlib.h>
int main()
{   
    int k,i,j,n;
    int row,col,newRow,newCol; 
int square[20][20];  //boyut arttırılabilir
    printf("matrisin boyutunu giriniz...\n");
scanf("%d",&n);
    for(i=0;i<n;i++) {
        for(j=0;j<n;j++) {
                square[i][j]=0;
        }
    }

    row=1;
    col=(n+1)/2;
    k=1;
    square[row-1][col-1]=k;


    for(k=2;k<=n*n;k++)
    {
        newRow=row-1;
        newCol=col+1;
        if (newRow==0&&newCol==(n+1))
        {
            newRow=row+1;
            newCol=n;
            row=newRow;
            col=newCol;
            square[row-1][col-1]=k;
        }
        else
        {
            while(newRow==0) //while if ile degistirilebilir
            {
            newRow=n;
            }
            while(newCol==(n+1))
            {
                newCol=1;
            }
            if(square[newRow-1][newCol-1]==0)
            {
                row=newRow;
                col=newCol;
                square[row-1][col-1]=k;
            }
            else
            {
                newRow=row+1;
                newCol=col;
                while(newRow==(n+1))
                {
                    newRow=1;
                }
                    row=newRow;
                    col=newCol;
                    square[row-1][col-1]=k;
            }
        }
    }
printf("%d*%d magic square:\n",n,n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",square[i][j]);
}
printf("\n");
}
     system("pause");
    return 0;
}

No comments:

Post a Comment