Magic Square: - : Code
Magic Square: - : Code
CODE: -
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
system("cls");
int i,j,rows,col,diagonal_1=0,diagonal_2=0,m,n,k=0,sum_rows=0,sum_col=0,flag=0;
scanf("%d",&rows);
col=rows;
int a[rows][col];
if(rows%2!=0)
m=0;
n=rows-1;
//If 8 1 6
// 3 5 7
// 4 9 2
for(i=0;i<rows;i++)
for(j=0;j<col;j++)
printf("a[%d][%d] =>",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<rows;i++)
for(j=0;j<col;j++)
printf("%d\t",a[i][j]);
printf("\n");
printf("\n\n=======================\n\n");
for(i=0;i<rows;i++)
diagonal_1+=a[i][i];
diagonal_2+=a[m][n];
m++;
n--;
if(diagonal_2==diagonal_1)
flag=1;
else
flag=0;
exit(0);
}
//Finding Sum of Rows
for(i=0;i<rows;i++)
sum_rows=0;
for(j=0;j<col;j++)
sum_rows+=a[i][j];
k++;
if(diagonal_1==sum_rows)
flag=1;
else
flag=0;
exit(0);
k=0;
for(i=0;i<col;i++)
sum_col=0;
for(j=0;j<rows;j++)
sum_col+=a[j][i];
}
k++;
if(diagonal_1==sum_col)
flag=1;
else
flag=0;
printf("\n\n[+]Even Though Diagonals and Rows Sum are Equal but Sum of Columns
are not Equal,so Not A MagicSquare\n\n");
exit(0);
if(flag==1)
else
getch();
return main() ;
return(0);
ALGORITHM: -
1) First the user will input the number of rows.
2) Then it will check the whether the number of rows is odd or not.
3) If it is odd, it will accept the elements for matrix.
4) But if it’s not, then it prompts to enter the odd number and restart the program.
5) When the user has entered the elements, the sum of elements of each row, column
and both the diagonals.
6) Then it will compare all the sums.
7) If all the sums are equal, then it will display that it is a magic square.
8) But if they are not equal then it will display that it is not a magic square.
OUTPUTS: -