Programming with Passion

Make the best out of everything.

Saturday, 4 February 2017

Magic Sqaure of n order with C++

Magic Sqaure of n order with C++

3X3 Magic Sqaure
#include<iostream.h>
#include<conio.h>
void main()
{  clrscr();
int i,j,k,n,a[10][10],sum=0;;
cout<<"Enter a odd number \n";
cin>>n;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=0;
j=n/2;
k=0;
for(i=1;i<=n*n;i++)
{
if(k<0)k=n-1;
if(j>(n-1))j=0;
a[k][j]=i;
if(i%n==0)
++k;
else
{
--k;
++j;
}
} clrscr();
cout<<"Magic Square of "<<n<<"X"<<n<<" is as given:\n";
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]/10==0)cout<<" ";
cout<<a[i][j]<<" ";
}
cout<<"\n";
}for(j=0;j<n;j++)
sum+=a[0][j];
cout<<"\nWhere sum of all the elements of columns, rows and diagonal is "<<sum;
getch();
}
Happy Coding. 
Also watch My channel on Youtube. https://www.youtube.com/watch?v=yHJmz9NNklk&t=3s

No comments:

Post a Comment