2

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?

user3386109
  • 34,287
  • 7
  • 49
  • 68
Divyanshu Varma
  • 122
  • 3
  • 17
  • 1
    [`a == b == c ==...` doesn't do what you expected](https://stackoverflow.com/q/8889522/995714) – phuclv Jul 29 '17 at 06:16
  • On a separate note it would be good to initialize variables and array's elements `c[5], r[5], d1, d2 ` with 0. Although the actual fault of your problem is in `if` statement. – MKR Jul 29 '17 at 06:17
  • 1
    Your code has an error on one of the diagonals, see my updated answer. – Rob Anthony Jul 29 '17 at 14:40

2 Answers2

1

You can't chain the equality operator like that. The expression

c[0] == c[1]

evaluates to either 0 or 1, so the expression

c[0] == c[1] == c[2]

is only true when

  • c[0] and c[1] are equal, and c[2] is 1, or
  • c[0] and c[1] are not equal, and c[2] is 0

You can use the && operator (logical AND) to write the if statement like this

if ( c[0] == c[1] && c[0] == c[2] && ...
user3386109
  • 34,287
  • 7
  • 49
  • 68
1

This doesn't work because the result of the first == would be true or false which would not be equal to the integer in the second. You need

If(c[1] == c[2] && c[2] == c[3] && c[3] == c[4]  etc

Also , the logic for your second diagonal calculation is incorrect. As x==y, ms[x][y] is the same as ms[y][x]. You are working out d1 twice! Instead, you need:

d2 += ms[4-x][y];
Rob Anthony
  • 1,743
  • 1
  • 13
  • 17