Write a c program to check whether the given matrix is a magic square matrix or not.
A matrix is magic square matrix, if all rows sum, columns sum and diagonals sum are equal.
Example:
8 1 6
3 5 7
4 9 2
is the magic square matrix. As you can see numbers in first row add up to 15 (8 + 1 + 6), so do the numbers of 2nd row 3 + 5 + 7. Also the number in the last row 4 + 9 + 2. Similarly, the columns all add up to the same number 15. Hence, this matrix is a magic square matrix.
The Program
#include <stdio.h> | |
void main() { | |
int A[50][50]; | |
int i, j, M, N; | |
int size; | |
int rowsum, columnsum, diagonalsum; | |
int magic = 0; | |
printf("Enter the order of the matrix:\n"); | |
scanf("%d %d", &M, &N); | |
if(M==N) { | |
printf("Enter the elements of matrix \n"); | |
for(i=0; i<M; i++) { | |
for(j=0; j<N; j++) { | |
scanf("%d", &A[i][j]); | |
} | |
} | |
printf("\n\nMATRIX is\n"); | |
for(i=0; i<M; i++) { | |
for(j=0; j<N; j++) { | |
printf("%3d\t", A[i][j]); | |
} | |
printf("\n"); | |
} | |
// calculate diagonal sum | |
diagonalsum = 0; | |
for(i=0; i<M; i++) { | |
for(j=0; j<N; j++) { | |
if(i==j) { | |
diagonalsum = diagonalsum + A[i][j]; | |
} | |
} | |
} | |
// calculate row sum | |
for(i=0; i<M; i++) { | |
rowsum = 0; | |
for(j=0; j<N; j++) { | |
rowsum = rowsum + A[i][j]; | |
} | |
if(rowsum != diagonalsum) { | |
printf("\nGiven matrix is not a magic square"); | |
return; | |
} | |
} | |
// calculate column sum | |
for(i=0; i<M; i++) { | |
columnsum = 0; | |
for(j=0; j<N; j++) { | |
columnsum = columnsum + A[j][i]; | |
} | |
if(columnsum != diagonalsum) { | |
printf("\nGiven matrix is not a magic square"); | |
return; | |
} | |
} | |
printf("\nGiven matrix is a magic square matrix"); | |
} else { | |
printf("\n\nPlease enter the square matrix order(m=n) \n\n"); | |
} | |
} |
Sample Output
Read more about C Programming Language and read the C Programming Language (2nd Edition). by K and R.
Related Programs
To get regular updates on new C programs, you can Follow @c_program
You can discuss these programs on our Facebook Page. Start a discussion right now,
Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link