Get Email Subscription

Enter your email address:

Delivered by FeedBurner

Tuesday, April 20, 2010

This is a program for generating a magic square (C++)


#include< String.H>
#include< StdLib.H>
#include< IOManip.H>
#include< IOStream.H>
 
#include "MagicSquare.H"
 
void showMatrix(int i,int j,int Matrix[][MAXSIZE])
{       
        cout<<"Square Matrix :"< < endl;
        char *s=new char[4];
        s[0]='\0';
 
        for(int x=0;x< i;x++)
        {
               for(int y=0;y
               {
                       itoa(Matrix[x][y],s,10);
                       if(strlen(s)<=1)
                       {                              
                               s[2]=s[0];
                               s[0]='0';
                               s[1]='0';                             
                               s[3]='\0';
                       }
                       else if(strlen(s)==2)
                       {
                               s[2]=s[1];
                               s[1]=s[0];
                               s[0]='0';                             
                               s[3]='\0';
                       }
                       cout< < setw(4)< < s;
               }
               cout< < endl;
        }
}
 
void magicSquare(int n)
{
        int squareMatrix[MAXSIZE][MAXSIZE]={0};
        int k=0,l=0;
 
        if( (n>(MAXSIZE)) || (n<1) )
        {
               cerr<<"Error! Size out of range"< < endl;
               return;
        }
        else if(!(n%2))
        {
               cerr<<"Error! n is Even"< < endl;
               return;
        }
        //showMatrix(n,n,squareMatrix);
 
        int key=1;
        int i=0;
        int j=(n-1)/2;
 
        squareMatrix[i][j]=key++;
 
        int max=n*n;
 
        while(key<=max)
        {
               //Rule 1:
               //      Move 1 UP & 1 Left
               //      If no element exists insert key their
               //Rule 2:
               //      Come To Original Position & Move 1 Down
               //      Insert key their & then follow rule 1 or 2
 
               if(i-1<0)k=n-1;else k=i-1;
               if(j-1<0)l=n-1;else l=j-1;
 
               if(squareMatrix[k][l])
               {
                       i=(i+1)%n;//capable of dealing with boundry
               }
               else
               {
                       i=k;
                       j=l;
               }
 
               squareMatrix[i][j]=key++;
 
        }
 
        showMatrix(n,n,squareMatrix);
}
 
void main()
{       
        magicSquare(19);
        char s[3]={0};
        cin.getline(s,2);
 }

Related Posts by Categories



0 comments:

About This Blog

Lorem Ipsum

  © Blogger templates Newspaper III by Ourblogtemplates.com 2008

Back to TOP