C Program to Check whether Matrix is Magic Square or Not ?

C Program to Check whether entered matrix is magic square or not ?

What is Magic Square :

  1. A magic square is a simple mathematical game developed during the 1500.
  2. Square is divided into equal number of rows and columns.
  3. Start filling each square with the number from 1 to num ( where num = No of Rows X No of Columns )
  4. You can only use a number once.
  5. Fill each square so that the sum of each row is the same as the sum of each column.
  6. In the example shown here, the sum of each row is 15, and the sum of each column is also 15.
  7. In this Example : The numbers from 1 through 9 is used only once. This is called a magic square.
Magic Square C Program
#include<stdio.h>
#include<conio.h>

void main()
{
int size,a[4][4];
int i,j=0;
int sum,sum1,sum2;
int flag=0;
clrscr();

printf("Enter matrix : ");
for(i=0;i<4;i++)
    {
    for(j=0;j<4;j++)
    scanf("%d",&a[i][j]);
    }

printf("Entered matrix is : nn");
for(i=0;i<4;i++)
{
    printf("n");
        for(j=0;j<4;j++)
        {
        printf("t%d",a[i][j]);
        }
}

//------for diagondal elements---------
sum=0;
for(i=0;i<4;i++)
    for(j=0;j<4;j++)
    {
    if(i==j)
    sum=sum+a[i][j];
    }
//-------------for rows--------------

for(i=0;i<4;i++)
{
    sum1=0;
    {
    for(j=0;j<4;j++)
    sum1=sum1+a[i][j];
    }
    if(sum==sum1)
        flag=1;
    else
        {
        flag=0;
        break;
        }
}
//-------------for colomns----------------
for(i=0;i<4;i++)
{
    sum2=0;
    for(j=0;j<4;j++)
    {
    sum2=sum2+a[j][i];
    }
    if(sum==sum2)
        flag=1;
    else
        {
        flag=0;
        break;
        }
}
//----------------------------------------
if(flag==1)
    printf("nntMagic square");
else
    printf("nntNo magic square");
//-----------------------------------------
getch();
}

Note :

Sum of Row1 = Sum of Row2 [Sum of All Rows must be Same]
Sum of Col1 = Sum of Col2 [Sum of All Cols must be Same]
Sum of Left Diagonal = Sum of Right Diagonal

Share this

Related Posts

Previous
Next Post »