vendredi 28 juillet 2017

Why is if not working in my Magic Square program

This is a program in C to check if a matrix is a Magic Square or not. Sums of all rows and columns, as well as both the diagonals, are equal to 65. This shows up in printf statements. Yet the if-else returns 0 instead of 1. Why?

#include<stdio.h>

int c[5], r[5];
int d1, d2;
int ms[5][5] = {
{25, 13, 1, 19, 7},
{16, 9, 22, 15, 3},
{12, 5, 18, 6, 24},
{8, 21, 14, 2, 20},
{4, 17, 10, 23, 11}};

//to calculate sums of every row, column and both diagonals
void sumUp() {
for (int x = 0; x < 5; x++)
    for (int y = 0; y < 5; y++) {
        r[x] += ms[x][y];
        c[x] += ms[y][x];
        if (x == y) {
            d1 += ms[x][y];
            d2 += ms[y][x];
        }
    }
}


//prints sums calculated
//returns 1 if all sums equal
int isMagic() {

printf("\n%d", r[0]);
printf("\n%d", r[1]);
printf("\n%d", r[2]);
printf("\n%d", r[3]);
printf("\n%d", r[4]);
printf("\n%d", c[0]);
printf("\n%d", c[1]);
printf("\n%d", c[2]);
printf("\n%d", c[3]);
printf("\n%d", c[4]);
printf("\n%d", d1);
printf("\n%d", d2);

//every sum prints equal to 65
if (c[0] == c[1] == c[2] == c[3] == c[4] == r[0] == r[1] == r[2] == 
r[3] == r[4] == d1 == d2) //yet this does not work
    return 1; 
else 
    return 0;
}

void show() {
if (isMagic())
    printf("\nYes, Magic");
else
    printf("\nNot Magic");

}

int main() {

sumUp();

show();
return 0;
}

Exactly why is if-else returning 0? Why is control going to else part when clearly all sums are equal?

Aucun commentaire:

Enregistrer un commentaire