title: print a mxn matrix spirally - java
body: <p>I am trying to print a mxn size matrix in a spiral manner. I tried to work this code through Java and I was able to print the spiral correctly if rows = columns.
  For unequal rows and columns I tend to have repetitions in printing. So it prints all the way to the center correctly but then it repeats one or more elements. I tried debugging but could not reach far.
  Can anyone help me with this?
  Here is the code I have got so far.</p>
  
  <pre><code>public class SpiralMatrix {
  public static void main (String args[]){
      int[][] mat = { {1, 2,  3,  4,  5},
                      {6, 7,  8,  9,  10},
                      {11,12, 13, 14, 15}};
      int i,n=3,m=5,r=m-1,q=n-1;
      while(q&gt;0 &amp;&amp; r&gt;0){
          for(i=m-1-r;i&lt;=r;i++){
              System.out.println(mat[m-1-r][i]);
          }
          for(i=n-1-q+1;i&lt;=q;i++){
              System.out.println(mat[i][r]);
          }
          for(i=r-1;i&gt;=m-1-r;i--){
              System.out.println(mat[q][i]);
          }
          for(i=q-1;i&gt;=n-1-q+1;i--){
              System.out.println(mat[i][n-1-q]);
          }
          q--;
          r--;
      }
  }
  }
  </code></pre>
  
  <p>The output of this is as follows:</p>
  
  <pre><code>1
  2
  3
  4
  5
  10
  15
  14
  13
  12
  11
  6
  7
  8
  9
  8
  7
  </code></pre>
  
  <p>So after reaching the middle value 9 it tracks back to 8 and 7.
  PS: This is not a homework, I am brushing up my skills for interviews. And please go easy on me, I am a life long learner!
  Thanks! I will appreciate your help.</p>