Thursday, July 5, 2012

Miscellaneous - I [Magic Square]



Magic Square or Wondrous Square – A odd size square matrix having all sums are equal to each other, like – sum of each row, each  column, sum of left diagonal and right diagonal are have to equal.



//Magic Square or Wondrous Square

#include <stdio.h>
#include <conio.h>

  void main()
      {
           int j,i,row,col;
           int f=0,sr=0,sc=0,sdl=0,sdr=0,N;
           int magic[20][20];
           clrscr();
           printf("\n\tSize of Matrix (Preffered an Odd No) : ");
           scanf("%d",&N);
           for(i=0;i<N;i++)
              {
                   for(j=0;j<N;j++)
                        {
                            magic[i][j]=0;
                        }
              }
           row = N-1;
           col = N/2;
           magic[row][col] = 1;
           for (i = 2; i <= N*N; i++)
              {
                   if (magic[(row + 1) % N][(col + 1) % N] == 0)
                        {
                            row = (row + 1) % N;
                            col = (col + 1) % N;
                        }
                   else
                        {
                            row = (row - 1 + N) % N;
                        }
                   magic[row][col] = i;
              }

           for (i = 0; i < N; i++)
              {
                   f=0;
                   sr=sc=0;
                   printf("\t");
                   for (j = 0; j < N; j++)
                        {
                            sr=sr+magic[i][j];
                            sc=sc+magic[j][i];
                            if(i+j==N-1)
                                {
                                     sdr=sdr+magic[i][j];
                                }
                            if(i==j)
                                {
                                     sdl=sdl+magic[i][j];
                                }
                            printf("%3d ",magic[i][j]);
                        }
                   if(sr!=sc)
                        {
                            f=1;
                        }
                   printf("   Sum : Row    %d  Col  %d \n",sr,sc);
              }
                   if(f==0 && sdl!=sdr)
                        {
                            f=1;
                        }
                   printf("\n\t\t\t  Sum Left Dig.   %d    Right Dig   %d",sdl,sdr);
                   if(f==1)
                        {
                            printf("\n\n\t\tAll sums are not equal, it is not a Magic Square");
                        }
                   else
                        {
                            printf("\n\n\t\tIt is a Magic Square");
                        }
           getch();
      }

No comments: