C Program to Check whether Matrix is Magic Square or Not

This page has a C Program to Check whether Matrix is Magic Square or Not. It is clear that, this C program will Check whether the given any Matrix is Magic Square or not. The magic square is a mathematical game and had been developed during the year 1500. The Magic Square is divided into equal number of rows and columns. Filling of each square with a number in the Magic Square Matrix starting from 1 to end-number ( where end-number = No of Rows X No of Columns ) You can use a number only once in the Magic Square Matrix. We should fill each square in the Magic Square Matrix and so that the sum of each row is the same as the sum of each column. The below given C program will Check whether the given any Matrix is Magic Square or not. Kindly check out the program to Check whether the given Matrix is Magic Square or not.

Magic Square Matrix Program

#include<stdio.h>

int main(){

int M[20][20];

int m, n, i, j, s1=0, s2=0, s3=0, set;

printf("

Enter the Row and Column sizes of Square Matrix : ");

scanf("%d %d", &m, &n);

if(m==n){

printf("



Enter the Matrix elements one by one

");

for (i = 1; i<=m; i++)

for (j = 1; j<=n; j++)

scanf("%d", &M[i][j]);

printf("

The Given Matrix is :

");

for (i = 1; i<=m; i++){

for (j = 1; j<=n; j++)

printf(" %d ", M[i][j]);

printf("

");

}

for (i = 1; i <= m; ++i) // For sum of Diagnal

for (j = 1; j <= n; ++j)

if (i == j)

s1 = s1 + M[i][j];

for (i = 1; i<=m; i++) { // Checking for sum of each Rows

for (j = 1; j<=n; j++) {

s2 = s2 + M[i][j];

}

if (s1 == s2)

set = 1;

else {

set = 0;

break;

}

s2=0;

}

for (i = 1; i<=m; i++) { // Checking for sum of each Columns

for (j = 1; j<=n; j++) {

s3 = s3 + M[j][i];

}

if (s1 == s3)

set = 1;

else {

set = 0;

break;

}

s3=0;

}

if (set == 1)

printf("



The Given Matrix is Magic square");

else

printf("



The Given Matrix is not Magic square");

}

return(0);

} Sample Output:

Enter the size of Square Matrix : 3 3

Enter the Matrix elements one by one

8

1

6

3

5

7

4

9

2

The Given Matrix is :

8 1 6

3 5 7

4 9 2

The Given Matrix is Magic square

Related Popular Posts: