title: Looping in a spiral
body: <p>A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fellow SO'ers could come up with a better solution.</p>
  
  <p>I'm posting my solution as an answer to this question.</p>
  
  <p><strong>Example Output:</strong></p>
  
  <p>For a 3x3 matrix, the output should be:</p>
  
  <p>(0, 0)
  (1, 0)
  (1, 1)
  (0, 1)
  (-1, 1)
  (-1, 0)
  (-1, -1)
  (0, -1)
  (1, -1)</p>
  
  <p><img src="https://i.stack.imgur.com/kjR4H.png" alt="3x3 matrix"></p>
  
  <p>Furthermore, the algorithm should support non-square matrices, so for example for a 5x3 matrix, the output should be:</p>
  
  <p>(0, 0)
  (1, 0)
  (1, 1)
  (0, 1)
  (-1, 1)
  (-1, 0)
  (-1, -1)
  (0, -1)
  (1, -1)
  (2, -1)
  (2, 0)
  (2, 1)
  (-2, 1)
  (-2, 0)
  (-2, -1)</p>
  
  <p><img src="https://i.stack.imgur.com/NE82F.png" alt="5x3 matrix"></p>