Magic Square

I am tasked in a school assignment to create a magic square. I was given a peice of code that is was supposed to use. So I'm having trouble figuring out how to place the numbers in the magic square. Something doesn't seem right with the code I was given. I think maybe it was incomplete or maybe wrong. I've been working on this all day and it's time to move on and start studying for the rest of my finals. Can anyone point me in the direction of my mistake. I'm not asking for a direct answer but maybe something along the lines of a good push in the right direction would greatly be appreciated. My code outputs the correct number of numbers they just aren't continuing to add numbers to the square.

I beleive my mistake is somewhere in between lines 22-42.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354`` ``````#include #include using namespace std; int main() { int row, col; int n = 7; int magic[7][7]; for(int r=0 ; r
Last edited on
You're going out of bounds in quite a few places and causes access violations on my machine and crashes. However, is this the output you were looking for?
 ``` 28 19 10 1 48 39 30 29 27 18 9 7 47 38 37 35 26 17 8 6 46 45 36 34 25 16 14 5 4 44 42 33 24 15 13 12 3 43 41 32 23 21 20 11 2 0 40 31 22```

I made a few changes, you seem like you're all but there, but just missing a few things.
that's what I need it to output. I'm not sure how to fill the square in correctly with my code though. Got any ideas how to fix it?
Last edited on
Your code is almost perfect. There is a few issues with lines 24-41. Some times when you assign a value to the matrix, you're jumping out of bounds. The values of row/col are from 1-7. Arrays allow access from 0-6.

To rectify your problem, wherever you assign a value to matrix, you need to assign it to row - 1 and col - 1.
Thanks for the help but I now have a new problem. I made the changes and it resized my square output to 3x3 square. I'm so confused.
There were only three places that you needed to change row and column. The code you posted above is right with the exceptions of these three lines:

Line 24: `magic[row][col]=1;`
To: `magic[row - 1][col - 1]=1;`

Line 36: `else if(magic[row][col]!=0)`
To: `else if(magic[row - 1][col - 1]!=0)`

Line 41: `magic[row][col]=i;`
To: `magic[row - 1][col - 1]=i;`
ok, I had to make one more change to the second for statement where
`i<(n*n)`
`i<=(n*n)`