Write a Program to check for Magic Squares in c language

Magic Squares
In any magic square, the numbers in every row, column, and diagonal all have the same magic sum.
Now, your challenge is to create a program that would check to see if the series of numbers
below is a magic square.Make sure you take into account all of the possibilities!!

13          8         12     1
2          11         7      14
3          10         6      15
16         5          9      4 

Ans :

#include<stdio.h>

int magic[][4] = {13,8,12,1,2,11,7,14,3,10,6,15,16,5,9,4};

int CheckRow() {
    int i, j, firstRow = 0, sum = 0;
    for(i = 0; i<4; i++) {
    firstRow += magic[0][i]; // find total of first row
    }
    for(i = 1; i<4; i++) {
    sum = 0;
    for(j = 0; j<4; j++) {
        sum += magic[i][j];
    }
    if(sum != firstRow) return 0;
    }
    return firstRow;
}

int CheckColumn(int presum) {
    int i, j, sum = 0;
    for(i = 0; i<4; i++) {
    sum = 0;
    for(j = 0; j<4; j++) {
        sum += magic[j][i];
    }
    if(sum != presum) return 0;
    }
    return 1;
}


int CheckDiagonal(int presum) {
    int i,sum = 0, c = 3;
    for(i = 0; i<4; i++) sum += magic[i][i]; //upper left to lower right 0,0 to 3,3
    if(sum != presum) return 0;
    sum = 0;
    for(i = 0; i<4; i++) {
    sum += magic[i][c--]; // upper right to lower left, 0,3 to 3,0
    }
    if(sum != presum) return 0;
    return 1;
}

void Find() {
    int presum = CheckRow();
    if(presum == 0) {
    printf("Not a magic square\n");
    return;
    }
    if(CheckColumn(presum) == 0) {
    printf("Not a magic square\n");
    return;
    }
    if(CheckDiagonal(presum) == 0) {
    printf("Not a magic square\n");
    return;
    }
    printf("Magic square\n");
}
void main() {
    Find();
    getch();
}

0 comments:

Post a Comment