Program to Print Matrix in Spiral format




package javaFixer;

/**
 * Program #2 Program To Print Matrix in Spiral
 * @author JavaFixer
 *
 */
public class SpiralMatrix {
 public static void main(String[] args) {
  int m=5;// No of Rows
  int n=4;// No of Columns
  int[][] arr = new int[m][n];
     int c1=0; int c2 = n-1;
     int r1=0; int r2 = m-1;
     int count = 1;
     
     while(count<=(m*n)){
      for(int i=c1;i<=c2;i++){
       arr[r1][i] = count;
       count++;
      }
      for(int i=r1+1;i<=r2;i++){
       arr[i][c2] = count;
       count++;
      }
      for(int i=c2-1;i>=c1;i--){
       arr[r2][i] = count;
       count++;
      }
      for(int i=r2-1;i>=r1+1;i--){
       arr[i][c1] = count;
       count++;
      }
      r1++;r2--;c1++;c2--;
     }
     
 for(int i=0;i<m;i++)
           {
               for(int j=0;j<n;j++)
                   {
                       System.out.print(arr[i][j]+ "\t");
                   }
            System.out.println();
           }
 }
}


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