C Program for find a matrix is magic square.
/*this program input the a square matrix and after checked that print the message entered matrix is magic
square or not*/
#include<stdio.h>
#include<conio.h>
void main()
{
int
matrix[10][10],n,i,j,r_sum,c_sum,rd_sum,ld_sum;
int sum[10],f=0;
r_sum=c_sum=rd_sum=ld_sum=0;
clrscr();
printf("Enter the Size of Square Matrix
:");
scanf("%d",&n);
printf("Enter the Matrix :");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&matrix[i][j]);
printf("Enterd Matrix is :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d\t",matrix[i][j]);
printf("\n");
}
for(i=0;i<n;i++)
sum[i]=0;
for(i=0;i<n;i++)
{ r_sum=0;
c_sum=0;
for(j=0;j<n;j++)
{
r_sum=r_sum+matrix[i][j];
c_sum=c_sum+matrix[j][i];
if(i==j)
ld_sum=ld_sum+matrix[i][j];
if((i+j)==n-1)
rd_sum=rd_sum+matrix[i][j];
}
sum[i]=r_sum;
sum[i+n]=c_sum;
}
sum[n+i]=rd_sum;
sum[n+i+1]=ld_sum;
r_sum=sum[0];
for(i=0;i<(n*2+2);i++)
if(r_sum!=sum[i])
{
f=1;
break;
}
if(f==0)
printf("\n\tits a Magice
Square.");
else
printf("\n\tits not a Magice
Square.");
getch();
}
Output:
Enter the Size of
Square Matrix : 3
2 7 6
2 7 6
9 5 1
4 3 8
It’s a Magic Square.
THIS IS NOT A MAGIC SQUARE DUDE :/
ReplyDeletethank you for showing your interest.
Deletefirst read what is magic square from wiki
http://en.wikipedia.org/wiki/Magic_square
then just try to understand the code. happy programming..