Hello everyone, I hate to make my first question as my first post, I would like to become a part of this seemingly great community, but I need to ask a question because I am stumped.

I need to create a Magic Square. This is my homework assignment, and I have spent 3 days now trying to figure it out. My instructor has not responded to my questions via email and hopefully you guys can help with this assignment.

Here are the instructions:

"
A magic square is an n x n matrix in which each of the integers 1,2,3...n 2 appears exactly once and all column sums, row sums, and diagonal sums are equal. For example, the following is a 5 x 5 magic square in which all of the sums add up to 65:

The following is a procedure for constructing an n x n magic square for any odd integer n. Place 1 in the middle column of the top row. Then after integer k has been placed, move up one row and one column to the right to place the next integer k + 1, unless one of the following occurs:

* If a move takes you above the top row in the ith column, move to the bottom of the ith column and place k + 1 there
* If a move takes you outside to the right of the square in the ith row, place k + 1 in the ith row at the left side.
* If a move takes you to an already filled square or if you move out of the square at the upper right-hand corner, place k + 1 immediately below k.

Write a program to construct n x n magic square for any odd value of n. "

My current code is started but the logic to actually enter the values I am stumped. I can only use <iostream>.
I know that I need to create a counting (for) loop to add the values into the array, but I literally am stumped. Hopefully someone will be up tonight who can help me out!

Thanks in advance, and I am happy to be on the site now.

#include <iostream>using namespace std;void fillMagicSquare(int newarray[][n], int size);int main(){int n = 1;cout << "Please enter the size of the matrix, it must be an odd number: " << endl; while (true) { cin >> n; int magic_square[n][n]; if (n%2==0) { cout << "You must choose an odd number! Choose Again: " << endl; } else { fillmagicsquare(arra, n); } }}void fillMagicSquare(int newarray[][n], int size){size = n2;int nsqr = n2 * n2;int i=0, j=n2/2;}

Thank you for the links that explain the workings of magic squares... I understand how the square "works" I am really just trying to lay it out into code.

Here is my best noob assumption on how the program would work.

I would assume a series of for loops that would place the appropriate values -- starting with 1 and moving up and to the right to place the next value (2), and to somehow figure out if a value has already been placed in that coordinate of the array, perhaps if the array gets set completely to 0 and then the program somehow checks to see if the value in that box is 0 and if it is, it will put the next value in it, if it is not zero then it will put the value in the box directly below it. That is at least how I think the logic would work.

Oh my, that is not even remembering that if it hits the top of the array, I have to somehow tell it to put the next value in the opposite side of the array. I feel like I know what it needs to do, but putting it into actual code is tough. This is an 8 week course, and it seems that we were just learning functions and operators a week or two ago, and now we are getting into crazy arrays, and searching them, my instructor does not explain anything and never answers emails. I basically have the internet and my book to help (and the book is not much help). I know that with practice it will eventually come naturally, but I have only been learning coding for less than 6 weeks. I aced my basic class because the teacher actually explained everything.

Anyways enough with my personal problems and frustration, I am asking for help, I am not asking for the code, I just feel like I do not even know where to start building those loops.

0

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

You cannot declare a static array with a variable dimension. If you need that, you need to dynamically allocate the array. Take a look at this tutorial about dynamic memory :

3)
>> void fillMagicSquare(int newarray[][n], int size);

'n' is not a const value here, so it can't be used like this. In any case, as per my first remark, you should probably use dynamically allocated arrays, which are passed to a function slightly differently (as a pointer-to-pointer).

4)
>> size = n2;

You passed 'size' as a parameter to the function ... why do you overwrite that value ? What is 'n2' anyway ?

Start by fixing these problems, and you should have a working framework for the assignment. All that's left then is to :

(a) implement the algorithm for generating the magic square
(b) output-ing the result

Thank you for the response, I will use your suggestions and keep working at it.

For the mean time, I have been trying a different setup for the whole thing... check it out and see if it would be set up better.... There are notes inside the code to explain what I was thinking while I wrote some of this stuff.

#include <iostream>using namespace std;int getDim();int n2;int main(){int i;int j;int n = getDim(); // trying to get a value to 'n' that is the user provided odd number from the getDim function, but it always comes back 0.cout << "You chose a "<< n << "x" << n << " matrix" << endl; //this line is to test if the value for 'n' came back correctly./* below is where I declared the matrix using the coordinates 'n' that the user provided. int matrix[n][n]; I believe I get a compiler error from this line. Does an array have to be filled with a constant? !! THE CODE COMPILES WITHOUT ERROR IF I REMOVE THE BELOW LOOP. !! The reason being because I have not declared my matrix array, I have not declared it because I do notknow how to create an array with dynamic dimensions yet. Something my teacher decided to not teach but expect us to know*/ for (i = 0; i<n; i++) for(j = 0; j<25; j++) matrix [i][j] = 0;}int getDim(){int n = 0;cout << "Please enter the size of the matrix, it must be an odd number: " << endl; while (true) { cin >> n; if (n%2==0) { cout << "You must choose an odd number! Choose Again: " << endl; } else { n = n2; return (n2); } }}

"int matrix[n][n]; I believe I get a compiler error from this line. Does an array have to be filled with a constant? "
As Infinity08 just said before,you can't define an array like that.
The memory is allocated at compile time, but your program finds out the value of n only at run-time. If you didn't learned to allocate dinamicaly memory, you should try something like
int matrix[10][10];
It should be enough.

Thanks everyone!! Really good info, much appreciated. I will keep working and probably have a couple more questions here soon. Points will be awarded in the morning :-)

Okay to be honest, I borrowed some logic for the loops that will control the placement if the location that it is supposed to add a number is not a zero, OR if the location already has a number in it. I wrote it all from scratch, but I had to look at the setup of the loops in order to move the placement. I completely understand it when I actually look at the code, it sucks that it is so hard for me to just "think" it up in my head without having to melt my brain against the keyboard <_<

So.... everything is compiling, and the array seems to be filled correctly.

Yet I am stuck printing my array. I am forced again to put variables into the coordinates for the array. Feedback is needed, thanks....

To Print the Array, I am using code shown below, how can I print the array in proper format, and keep variables out of the array coordinates?

/* n is the length of each side (the dimensions) and r and c are just placeholders for the for loops.*/int r; int c; for (r = 0; r <= n; r++) for (c = 0; c <= n; c++) cout << matrix[r][c] << "/t" ;

There are several advanced concepts in play here. Dynamic memory management and possibly recursion. Getting a good program out of this will be easier if you tackle one of them at a time.

Start by "hard coding" the matrix size. Make it arbitrarily large (perhaps 100 x 100) so that you can build any magic square in it up to size 100. Having an upper limit of 100 shouldn't be a hardship for developing the code. After you have the algorithm debugged you can come back in install the dynamic arrays.

As far as building the magic square, it's not nearly as tough as the instructor would have you believe. :)

Start with the cell at 0,0 and place a 1 in it. Then move across the row, putting a value into each cell. When the row is full, move to the next row and repeat. When you insert a value into a cell, test that the value does not violate the uniqueness rule for that row and column. The algorithm will need to be able to test all values from 1 to n for each cell, though not every value will be tried in every cell.

This will create a very nice pattern to the data so it will be easy to see if you "got it right".

The algorithm can be coded recursively. Nested loops are a start, but a recursive routine will be easier.

well I guess I wont get full credit on it since the algorithm is not correct, but thanks for the input Kent.

The problem with the print code that you gave me is that we have never learned fprintf or stdout so we are not allowed to use it.

Next time I will take a full semester coding class instead of short term (fast track) so we do not cover the entire book in 7 weeks. I am fresh with no coding knowledge, and like I said before, it seems like we were just practicing making variables and structuring arrays about a week or two ago, and now were all the way here.

I am making a new thread with my next assignment once I get some valid code written. (I am not here to cheat, just get help and guidance) so hopefully all your experienced coders will meet up with me on that thread when I make it.

Thanks again everyone. Sorry the code is flawed, it just does not come naturally for me.

>> I think they're learning C++, rather than C, and so are using the C++ streams (cout, etc.) for I/O. At least that's what his original code was using.

Showing my age, huh? :) If I don't go back and check the fine print I automatically revert to C.

0

Featured Post

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Introduction
This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more â€¦

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to useâ€¦