### A magic square is an n * n matrix of the integers 1 to n^2 such that the sum of each row, column, and diagonal is the same. The figure given below is an example of magic square for case n=5. In this example, the common sum is 65. Write C/C++ Program for magic square.

A magic square is an n * n matrix of the integers 1 to n^2 such that the sum of each row,
column, and diagonal is the same. The figure given below is an example of magic square for
case n=5. In this example, the common sum is 65. Write C/C++ Program for magic square.

#include<iostream>
using namespace std; OUTPUT FOR THE PROGRAM
int i,j,n,num, ms;
void magicsquare()
{

cout<<"Enter Size : ";
cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
ms[i][j]=0;
}
}

i=n/2;
j=n-1;
for(num=1;num<=n*n;num++)
{
if(i==-1 && j==n)
{
i=0;
j=n-2;
}
else
{
if(j==n)
j=0;
if(i<0)
i=n-1;
}
if(ms[i][j])
{
j=j-2;
i=i+1;
}
ms[i][j]=num;
j++;
i--;
}
cout<<"***********************************MATRIX********************************";

for(i=0;i<n;i++)
{

cout<<"\n\n\t\t";
for(j=0;j<n;j++)
{
cout<<ms[i][j]<<" ";
}
cout<<"\n\n";
}
cout<<"*************************************************************************"<<"\n";
}

int main()
{
magicsquare();
int l;
l=n*(n*n+1)/2;
cout<<"Sum of The Elements of each Row, column And Diagonal is "<<l<<"\n";
return 0;
}

For more such posts click the link:-http://svencrai.com/G8W