Programming with Passion

Make the best out of everything.

Wednesday 16 March 2016

Magic Grid

Try This Magic Grid in your Compiler

Input an odd number and it will give you NXN grid which is a magic grid i.e. on adding any row, column or diagonals elements the sum is same.


#include<iostream.h>
#include<conio.h>
int main()
{
 clrscr();

int g[11][11],i,j,m=0,n=0,a,b=1,p,q;
cout<<"Enter Grid Size(odd nos.\n";
cin>>a;
for(i=0;i<a;++i)
for(j=0;j<a;++j)
g[i][j]=0;
n=a%2;
for(i=0;i<a;++i)
{
for(j=0;j<a;++j)
{
g[m][n]=b++;
p=m--;q=n++;
if(m<=-1)m=a-1;
if(n==a)n=0;
if(g[m][n]!=0){m=p;n=q;++m; }
}
}
for(i=0;i<a;++i){

for(j=0;j<a;++j){
cout<<g[i][j]<<"  ";
if(g[i][j]<=9)cout<<" ";
}
cout<<"\n";   }
getch();

}

No comments:

Post a Comment