Check if a Square matrix is a magic square or not in 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 want to Learn How to Generate Magic Squares using C++

Steps to Check if a square matrix is a magic square or not

to check if a square matrix is a magic square in C++, you can follow these steps:

  1. In a traditional magic square, the requirement is that each number from 1 to n^2 (where n is the size of the square matrix) should appear exactly once in the square.
  2. Calculate the sum of the first row and store it in a variable (let’s call it magicSum).
  3. Iterate through each row and column to calculate their sums. If any row or column sum is not equal to magicSum, the matrix is not a magic square.
  4. Additionally, calculate the sums of both diagonals and check if they are equal to magicSum.

Code in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int size;
cout<<"\n\t==============================================\n\n";
cout<<"\t\t\tMAGIC SQUARE\n";
cout<<"\t==============================================\n\n";
cout<<"\tEnter size of Magic Square : \t";
cin>>size;
int arr[size][size];
int i,j,c1,c2;
int check[2*size];
for(i=0;i<2*size;i++)
 check[i]=0;
cout<<"\n\t\tNo element should repeat\n\n";
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
xyz:
cout<<"\tEnter Element ["<<i<<"]["<<j<<"] : ";
cin>>arr[i][j];
for(c1=0;c1<i;c1++)
for(c2=0;c2<size;c2++)
if(arr[i][j]==arr[c1][c2])
goto xyz;
for(c1=0;c1<j;c1++)
if(arr[i][c1]==arr[i][j])
goto xyz;
}
}
for(c1=0,i=0;i<size;i++,c1++)
{
for(j=0;j<size;j++)
{
check[c1]+=arr[i][j];
check[c1+size]+=arr[j][i];
}
}
c2=check[0];
for(c1=1;c1<(2*size)-1;c1++)
{
if(c2!=check[c1])
{
cout<<"\n\tSquare is not magic square \n\n";
cout<<"\n\tYOU ENTERED FOLLOWING SQUARE \n\n";
for(i=0;i<size;i++)
{
cout<<"\t\n\t";
for(j=0;j<size;j++)
{
cout<<arr[i][j]<<" ";
}
}
getch();
cout<<endl;
return 0;
}
}
cout<<"\n\tYeah... you won... You entered a perfect Magic Square \n\n";
cout<<"\n\tYOU ENTERED FOLLOWING SQUARE \n\n";
for(i=0;i<size;i++)
{
cout<<"\t\n\t";
for(j=0;j<size;j++)
{
cout<<arr[i][j]<<" ";
}
}
cout<<"\n\n\tSum of its each row and column is same = "<<check[0];
getch();
return 0;
}

Output

Check if a Square matrix is a magic square or not in C++

1 thought on “Check if a Square matrix is a magic square or not in C++”

Leave a Comment