Pages

  • Home
  • About & Contact
  • Archive
  • C Programming Examples

20 June 2012

Magic square program in C

What is Magic Square:- Square which contains further divided smaller N x N squares.Each square contains a number such that sum of each row ,column and diagonal is same,like if size of magic square is 3 x 3 then sum of each row,column and diagonal is 15and if 5 x 5 then value is 65.Sum of row,column or diagonal of magic square can be easily calculated by using the formula n(n^2 + 1)/2 .  Now coming towards the implementation of magic square program in c for odd size
The following steps will lead you to implement magic square.
Magic square program in C

Step 1:  Initialize the N x N array with 0 will be used to check the location is empty or not.
Step 2: make provisions to make the array circular i.e by using %.Place 1 at the middle location of 
the 1st row.
Step 3: create the loop for remaining (n*n)-1  numbers to be placed in magic square and place them by following rules:If the location in the upper row next column  is empty i.e 0 then place the value over there else place it at the row below the above thus get the magic square for odd size of square.

Magic square program in C


#include<stdio.h>
#include<conio.h>
void main()
{
    int sqr[25][25]={(0)},n,i,j,k,p,q;
    //clrscr();
     printf("enter size of magic squre:");
     label:
     scanf("%d",&n);
     if(n%2!=1||n>=25)
     {
               printf("Enter the odd value in the range of 25\n");
               goto label;
    }
    i=0;
    j=(n)/2;
    sqr[i][j]=1;
    for(k=2;k<=(n*n);k++)
   {
               p=i-1<0?n-1 : i-1;
               q=(j+1)%n;
               if(sqr[p][q]==0)
              {
                        i=p;
                        j=q;
              }
              else
                       i++;
              sqr[i][j]=k;
    }
    printf("\nHere is the magic square\n");
    for(i=0;i<n;i++)
    {
           for(j=0;j<n;j++)
                printf("%d\t",sqr[i][j]);
           printf("\n");
    }
}
Share your views regarding the given post via the comments section given below.
If you liked the post, please '+1' it & share it on other social networks.
Thank You.
Romil shah

1 comment:

  1. above program seems long check this one
    #include
    void main()
    {
    int i,j,d,n;
    puts("enter the dimension");
    scanf("%d",&d);
    int sq[d][d];
    for (n=1;n<=d*d;n++)
    {
    i=(d-n%d+1+2*((n-1)/d))%d;
    j=((d-1)/2+n-1-(n-1)/d)%d;
    sq[i][j]=n;
    }
    for (i=0;i<d;i++)
    {
    for (j=0;j<d;j++)
    printf("%d\t",sq[i][j]);
    printf("\n");
    }
    }

    ReplyDelete