C - spiral traversal of 2D array outwards (starting from center) and clockwise

Viewed 3518

I'm struggling with my assignment and need some help.

The program I have to code must traverse (more exactly - fill with natural numbers from 1 to N^2, but the traversal algorithm is what I struggle with) a 2D array A[N][N], where N is odd (1,3,5,7...), starting from center ( A[N/2][N/2] ) and moving spirally and clockwise.

Example (N=5):

25  10  11  12  13
24  9   2   3   14
23  8   1   4   15
22  7   6   5   16
21  20  19  18  17

I see the pattern : center=1 ; 1xUP, 1xRIGHT, 2xDOWN, 2xLEFT, 3xUP, 3xRIGHT, and so on ...

How can I implement this algorithm with loops? Time is ticking away and I'm stuck here ...

Will be happy to read some suggestions and receive help.

Thank you!

1 Answers
Related