Magic Square

hey so I have this project called the magic square f.x http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Magicsquareexample.svg/180px-Magicsquareexample.svg.png
the numbers shouldnt be always 15 for that case, but should be the same in every direction. addionally it could be 1x1, 2x2.. 3x3 or 50x50 so it should just return if all the sums are the same or not.

Right now im just trying it to get to calculate correctly the sum of the lines and rows, but getting wrong answers. hoping for the best ;)

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
#include <iostream>
#include <math.h>
#include<iostream>
#include<fstream>

using namespace std;


int main()
{
    int i; int j;
    int dsize;
    int row=0;
    int column=0;
    cin >> dsize;

    int dice[dsize][dsize];
    int ismagic[dsize*2+2];

    for (int i=0;i<dsize; i++ )
    {
        for (int j=0;j<dsize; j++)
        {
            cin>> dice[i][j];
            {
            ismagic[row]+=dice[i][j];
            ++row;}


        }
        {
        ismagic[column]+=dice[i][j];
        ++column;
        }


}               cout << ismagic[row];
        cout << ismagic[column];


    return 0;
}
closed account (o3hC5Di1)
Hi there,

Your code is a little bit messy, for instance, why do you need an anonymous code block line 32 to line 34?

To calculate the sum of rows and columns, you basically need to keep two counter-arrays, rowsum[] and colsum[]:

1
2
3
4
5
6
7
8
for (size_t x=0; x<array_size; ++x)  //this loop goes over the rows, "vertically"
{
    for (size_t y=0; y<array_size; ++y) //this loop goes over the columns (within the current row), "horizontally"
    {
        rowsum[x] += array[x][y];
        colsum[y] += array[x][y];
    }
}


Note that this supposes that rows and columns are the same size, but since it's a square that should be safe to assume.

Hope that helps, please do let us know if you have any further questions.

All the best,
NwN
cheers, its solved :)
Topic archived. No new replies allowed.