Generate Magic Squares using C++

A magic square is a square matrix (a two-dimensional array of numbers) in which the sum of the numbers in each row, column, and diagonal is the same. This constant sum is known as the “magic sum” or “magic constant.” Magic squares have been a subject of fascination and study for centuries due to their intriguing mathematical properties and historical significance.

You might also want to learn how to Check if a square Matrix is a magic square or not

Generating magic squares in C++ can be achieved using various algorithms. One common approach is the given below, which works for odd-sized squares. Here’s a C++ program to generate a magic square for an odd-sized square:

Code

#include<iostream>
#include<conio.h>
using namespace std; 
int main() 
{ 
cout<<"\n\t==============================================\n\n";
cout<<"\t\t\tGENERATE MAGIC SQUAREs\n";
cout<<"\t==============================================\n\n";
 int n;
do 
{
cout<<"\n\tEnter a number to find its Magic square:\n";
cout<<"\n\t(Number Must be odd) \t";
cin>>n;
}
while(n%2==0);
int m[n][n];
int i,j; 
for(i=0;i<n;i++)
for(j=0;j<n;j++)
m[i][j]=0;
 i = n/2; 
 j = n-1; 
 //assign values
 for (int num=1; num <= n*n; ) 
 { 
 if (i==-1 && j==n)
 { 
 j = n-2; 
 i = 0; 
 } 
else
 { 
 if (j == n) 
 j = 0; 
 if (i < 0) 
 i=n-1; 
 } 
 if (m[i][j]!=0)
 { 
 j -= 2; 
 i++; 
 continue;
 } 
 else
 m[i][j] = num++; 
 
 j++; i--; 
 } 
 
 // Print magic square
cout<<"\n\tMAGIC SQUARE OF "<<n<<" x "<<n <<"\n\twith sum of each row and column = "<<n*(n*n+1)/2<<" is \n\n"; 
 for (i=0; i<n; i++) 
 { 
 cout<<"\t";
 for (j=0; j<n; j++) 
 cout<<m[i][j]<<"\t"; 
 cout<<endl;
 } 
 cout<<endl;
 getch();
 return 0; 
}

Output

Generate Magic Squares using C++

1 thought on “Generate Magic Squares using C++”

Leave a Comment