Create a Magic Square
Grading Rubric
This project is worth 20 pts:
- 1 point for having your name and user-name at the top of the file.
- 15 points for generating a correct magic square of different sizes.
- 2 points for only accepting odd sizes.
- 1 point for having the output be beautiful.
- 1 point for clean, neat, well-indented code.
- The project is due at midnight on next Monday. You will receive a 10% per day penalty for lateness.
Instructions
A magic square is an n x n matrix in which each of the integers 1, 2, 3, ... , n2
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 the rows, columns, and diagonals add up to 65:
17 |
24 |
1 |
8 |
15 |
23 |
5 |
7 |
14 |
16 |
4 |
6 |
13 |
20 |
22 |
10 |
12 |
19 |
21 |
3 |
11 |
18 |
25 |
2 |
9 |
The following is a procedure for constructing an n x n
magic square for any odd integer n. Place 1 in the middle 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 jth column, move to the bottom of the jth
column and place the integer there.
- If a move takes you outside to the right of the square in the ith row, place the integer 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 an n x n magic square for any odd value of n between 1 and 15
inclusive. The program should also print out the magic square with good formatting so
that all values line up nicely under one another -- i.e., nice pretty columns. Use setw() for this.
Note: ask the user n and check that it is odd and is less
than or equal to 15. If it isn't, print an error message and exit.
Note: define your two-dimensional array to be 15x15 (even before
getting the user's choice). When the user chooses a smaller dimension, the code will simply use less of the array.
Submission
Submit your code to /home/cs/112/current/yourId/proj2/.