interpreting pseudo-code

I was given this assignment to do, but the pseudo-code doesn't make much sense to me, can anyone interpret this for me. (i'll explain why i'm confused down below)

Implement the following algorithm to construct magic n × n squares; it works only if n is odd.
Set row = n - 1, column = n / 2.
For k = 1 . . . n * n
Place k at [row][column].
Increment row and column.
If the row or column is n, replace it with 0.
If the element at [row][column] has already been filled
Set row and column to their previous value.
Decrement row.
Here is the 5 × 5 square that you get if you follow this method:
11 18 25 2 9
10 12 19 21 3
4 6 13 20 22
23 5 7 14 16
17 24 1 8 15

Write a program whose input is the number n and whose output is the magic square of order n if n is odd. (Horstmann, 2017-08-12, p. EX6-3)




So i find this pseudo-code confusing because:
1. its starts out with saying "set row = n - 1, column = n / 2. but with an array aren't row and column values supposed to be constant?
2. "For k = 1...n * n" is very confusing, it seems like the start of a for loop, but what follows after it isn't clear at all (at least to me)
3. Now it seems to be asking me to place "k" in the matrix, but i have no idea what k should be.
1. It's not the dimension of the array but start indexes. The dimension (as a magic sqare) is n x n.
2. I would guess they mean that k is the index (incremented by 1) that goes from 1 to n*n.
3. See 2,

1. its starts out with saying "set row = n - 1, column = n / 2. but with an array aren't row and column values supposed to be constant?
n, row and column are variables. n is your starting variable/parameter that must be specified.

2. "For k = 1...n * n" is very confusing, it seems like the start of a for loop, but what follows after it isn't clear at all (at least to me)
That's a for loop, in C++, it could be written as:
1
2
for (int k = 1; i <= (n*n); ++i) {
}


3. Now it seems to be asking me to place "k" in the matrix, but i have no idea what k should be.
That'll be something like:
 
matrix[row][col] = k;

And that implies there's a matrix variable of size n by n. In the example, n = 5.

EDIT: added @ne555's correction
Last edited on
You may find it easier to see the pattern if you use a larger n:

Input n (odd): 9

37 48 59 70 81  2 13 24 35
36 38 49 60 71 73  3 14 25
26 28 39 50 61 72 74  4 15
16 27 29 40 51 62 64 75  5
 6 17 19 30 41 52 63 65 76
77  7 18 20 31 42 53 55 66
67 78  8 10 21 32 43 54 56
57 68 79  9 11 22 33 44 46
47 58 69 80  1 12 23 34 45
for (int k = 1; k <= (n*n); ++k)
<= to include n*n
Topic archived. No new replies allowed.