Traversing the perimeter of a 2D array counterclockwise
<p>This is my first question on Stack Overflow, so please let me know if I am not following the community guidelines and conventions correctly.</p>

<p>What is a clever way to traverse the perimeter of a 2D array in a counterclockwise (or clockwise) direction from <code>row 0</code>, <code>column 0</code> (preferably without revisiting each element)?</p>

<p>Intuitively, I could write four <code>for</code> loops for each direction sequentially (i.e., write a <code>for</code> loop to traverse the left column, then write a <code>for</code> loop to traverse the bottom row, and so forth). But this solution feels "hard-coded".</p>

<p>Does there exist a "shortcut" method that takes advantage of some key insight on this pattern? Would this shortcut method also be efficient in terms of program runtime?</p>

<p>Thanks in advance.</p>

<hr>

<p>Edit for specificity:</p>

<p>Specifically, I am trying to traverse this 2D array counterclockwise from <code>row 0</code>, <code>column 0</code>, and print each element only once.</p>

<p>Suppose the array looks like this:<br>
<code>01 02 03 04 05
 06 07 08 09 10
 11 12 13 14 15
 16 17 18 19 20</code></p>

<p>My intended output is as follows:
<code>1, 6, 11, 16, 17, 18, 19, 20, 15, 10, 5, 4, 3, 2</code>.</p>

<p>Here is my current solution (this solution works):</p>

<pre><code>//Loop through the left side.
int i;
for (i = 0; i &lt; rows; i++)
    printf("%d, ", array[i][0]);

//Loop through the bottom side.
for (i = 1; i &lt; columns; i++)
    printf("%d, ", array[rows-1][i]);

//Loop through the right side.
for (i = rows-2; i &gt;= 0; i--)
    printf("%d, ", array[i][columns-1]);

//Loop through the top side.
for (i = columns-2; i &gt; 1; i--)
    printf("%d, ", array[0][i]);

//Print the last element.
printf("%d.\n", array[0][1]);
</code></pre>

<p>Personally, my solution seems straightforward and repetitive. I would like to know if there is a more creative solution.</p>

<p>Please let me know if any more clarification is needed.</p>