Magic Square help!

I have to write a program which checks the conditions of this specific 2D array:
const int Size = 3;
int a[][Size] = { { 4, 9, 2 }, { 3, 5, 7 }, { 8, 1, 6 } };


This is a magic square, as each row, col, and diagonal sum equals 15.

However, my program says that it is not a magic square, so there is an issue in the condition check.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <cmath>
using namespace std;

const int Size = 3;
bool isMagic(const int inArray[][Size]);

int main()
{
	int a[][Size] = { { 4, 9, 2 }, { 3, 5, 7 }, { 8, 1, 6 } }; //initially, 3 rows 3 cols

	if (isMagic(a))
	{
		cout << "This is a magic square" << endl;
	}
	else
	{
		cout << "This is NOT a magic square :(" << endl;
	}

	system("PAUSE");
	return 0;
}
bool isMagic(const int inArray[][Size])
{
	int MagicTotal;
	MagicTotal = Size*(pow(Size, 2) + 1) / 2.0;
	cout << "The magic square sum is: " << MagicTotal << endl;
	int condition;
	condition = 0;

	for (int i = 0; i < Size; i++)
	{
		for (int j = 0; j < Size; j++)
		{
			condition += inArray[i][j];
			if (condition == MagicTotal)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
}
you've got
1
2
3
4
for()
   for()
      if() return
      else return
you are stopping at the first iteration

please comment your code describing your approach
Is it stopping at the first iteration because its checking for the boolean condition?

I'm trying to construct the nested for loop and the condition variable where the condition variable is the total sum of the rows and columns

so condition =
row[0]col[0] + row[0]+col[1]+row[0]+col[2] = 15

Then the next condition is =
row[1]col[0]+row[1]+col[1]+row[1]+col[2] = 15

basically i'm checking if the sum of all rows, columns, and diagnols = 15
need urgent help!
Think about the iterations. If you find a magic you want to immediately return true. When would you want to return false?
Hasn't that been answered already?
1
2
3
4
5
6
7
8
9

for( int x = 0; x != Size; ++x ){
    for( int y = 0; y != Size; ++y ){
        condition += whatever[x][y];
    }
    if( condition != magicSum ) return false;
    condition = 0;
}
//if you get here, it means you have a magic strand or whatever you call it 


It should be quite obvious what part of your code you have to make changes to.
Last edited on
Topic archived. No new replies allowed.