Tuesday 4 September 2012

Print 2D array in spiral form.

/*
if array is 
1    2   3   4   5
6    7   8   9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

output:- 1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13

*/

#include<iostream.h>
#include<conio.h>

int matrix[5][5]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};

void spiralprint(int row,int col)
{
     int cstart=0,cend=col-1,rstart=0,rend=row-1,n=col*row;
     int count=0;
     while(count<n)
     {
                   for(int i=cstart;i<=cend;i++,count++)
                           cout<<"  "<<matrix[rstart][i];
                   rstart++;
                   for(int j=rstart;j<=rend;j++,count++)
                           cout<<"  "<<matrix[j][cend];
                   cend--;
                   for(int k=cend;k>=cstart;k--,count++)
                           cout<<"  "<<matrix[rend][k];
                   rend--;
                   for(int l=rend;l>=rstart;l--,count++)
                           cout<<"  "<<matrix[l][cstart];
                   cstart++;
     }
                   
}

int main()
{
    spiralprint(5,5);
    getch();
    return 0;
}

No comments:

Post a Comment