/* * To input a 3 X 3 matrix and check if it is a magic square * @author-Karan Narain(karan@iitk.ac.in) * */ #include int main() { int A[3][3],i,j,rowsum[3],colsum[3],diagsum[2],flag=0; //Flag is used to check if input is in the range 1 to 9 printf("Enter the elements of the 3 x 3 matrix(in the range 1 to 9)\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&A[i][j]); if((A[i][j]<1)|| (A[i][j]>9)) flag=1; } } if(flag==1) { printf("\nThe input elements should be in the range 1 to 9.\n"); return 0; } //Initialize the sum arrays diagsum[0]=0; diagsum[1]=0; printf("The matrix you entered is \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d ",A[i][j]); } printf("\n"); rowsum[i]=0; colsum[i]=0; } //The sums are calculated in separate loops for the sake of clarity //Calculate rowsums for(i=0;i<3;i++) { for(j=0;j<3;j++) { rowsum[i]=rowsum[i]+A[i][j]; } printf("\nThe sum of row %d is %d",i+1,rowsum[i]); } //Calculate colsums for(j=0;j<3;j++) { for(i=0;i<3;i++) { colsum[j]=colsum[j]+A[i][j]; } printf("\nThe sum of column %d is %d",j+1,colsum[i]); } //Calculate diagonal sums for(i=0;i<3;i++) { for(j=0;j<3;j++) { if(i==j) diagsum[0]=diagsum[0]+A[i][j]; if((i+j)==2) diagsum[1]=diagsum[1]+A[i][j]; } } printf("\nThe sum of main diagonal is %d",diagsum[0]); printf("\nThe sum of cross-diagonal is %d\n",diagsum[1]); printf("For a magic square of dimension 3,the sum should be 15\n"); //Check for equality of the sums for(i=0;i<2;i++) { for(j=0;j<2;j++) { if((rowsum[i]==rowsum[i+1]) && (rowsum[i]==colsum[i]) && (colsum[i]==colsum[i+1])) continue; else { printf("The given matrix is not a magic square\n"); return 0; } } } //Check with the diagonal sums as well if((rowsum[0]==diagsum[0]) && (diagsum[0]==diagsum[1])) printf("The given matrix is a magic square\n"); return 0; }