About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Monday, September 2, 2013

C Program to Check whether 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

2 comments:

zzzzz said...

Take a number N as input from user.
Find the sum of the digits of N(Lets call it digitSum).
Reverse the digits of digitSum(Lets call it reverse).
If product of digitSum and reverse is equal to the original number N, then N is magic number otherwise not a magic number.

Unknown said...

vai toma no cu fdp n taa judando seu merda do caralho vo te mata fela da puta