Skip to content

Instantly share code, notes, and snippets.

@snadahalli
Last active February 15, 2024 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save snadahalli/3598e3baa2c599a2e037f39556f96bbd to your computer and use it in GitHub Desktop.
Save snadahalli/3598e3baa2c599a2e037f39556f96bbd to your computer and use it in GitHub Desktop.
C Program to check if a given matrix is a magic square matrix or not.
#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");
}
}
@v0rade
Copy link

v0rade commented Nov 30, 2022

how we validate the same input like:
111
111
111
it must be detected as magic square

@arjun-v1
Copy link

Hey here in the code you didn't use int magic_square =0; or this variable or your not incrementing it so i think it is not required

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment