title: print 2-D array in spiral order
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/7042165/pattern-consisting-of-numbers-moving-in-clockwise-direction-around-a-rectangular">Pattern consisting of numbers moving in clockwise direction around a rectangular shape (length and breadth decreasing each time)</a>  </p>
  </blockquote>
  
  
  
  <p>How to print a 2 dimensional array in spiral order using JAVA? Please help, I don't have any idea.</p>
  
  <p>sample array:</p>
  
  <pre><code>1  2  3  4
  
  5  6  7  8
  
  9  10 11 12
  
  13 14 15 16
  </code></pre>
  
  <p>output:</p>
  
  <pre><code>1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
  </code></pre>
  
  <p>here is what i tried:</p>
  
  <p>public static void main(String[] args) {</p>
  
  <pre><code>    int[][] values = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
  
      for (int i = (values.length * values[0].length)-1, j = 0; i &gt; 0; i--, j++) {
            for (int k = j; k &lt; i; k++) {
                System.out.print(values[j][k]);
            }
  
            for (int k = j; k &lt; i; k++) {
                System.out.print(values[k][i]);
            }
  
            for (int k = i; k &gt; j; k--) {
                System.out.print(values[i][k]);
            }
  
            for (int k = i; k &gt; j; k--) {
                System.out.print(values[k][j]);
            }
      }
  
  }
  </code></pre>