C Program to find whether the given matrix is magic square or not.
Magic square:
// *a square array of numbers, usually positive integers, is called a magic square if the sums of the numbers in each row, each column, and both main diagonals are the same//.
Ex:
Enter the no.of rows
2
4 5
5 4
Output:
Given matrix is not a magic square.
Enter the no.of rows
3
4 9 2
3 5 7
8 1 6
Output:
Given matrix is a magic square.
Program:
#include<studio.h>
int main()
{
int n,i,j,count=0,sum=0,Sum1,sum2;
printf("enter the no.of rows");
scanf("%d",&n);
int a[n][n];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",a[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
sum=sum+a[i][j]; //sum of diagonals//
}
}
}
for(i=0;i<n;i++)
{
sum1=0;
for(j=0;j<n;j++)
{
sum1=sum1+a[i][j]; //sum of columns//
}
if(sum==sum1)
count++;
else
break;
}
for(i=0;i<n;i++)
{
sum2=0;
for(j=0;j<n;j++)
{
sum2=sum2+a[j][i]; //sum of rows//
}
if(sum==sum2)
count++;
else
break;
}
if(count==2*n)
printf("given matrix is magic square");
else
printf("given matrix is not a magic square");
return 0;
}
Nice solving
ReplyDeletePost a Comment