-
Notifications
You must be signed in to change notification settings - Fork 342
/
Print the array in spiral form
39 lines (37 loc) · 1.07 KB
/
Print the array in spiral form
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;
int main()
{
int arr[3][6] = { { 1, 2, 3, 4, 5, 6 },
{ 7, 8, 9, 10, 11, 12 },
{ 13, 14, 15, 16, 17, 18 } };
int i,t=0,b=2,l=0,r=5,dir=0; // t,b,l,r are pointers pointing to top, bottom, left and right of the 2D array
while(l<=r && t<=b)
{
if(dir==0) //printing from left to right
{
for(i=l;i<=r;i++)
cout<<arr[t][i]<<" ";
t++;
}
else if(dir==1) //printing from top to bottom
{
for(i=t;i<=b;i++)
cout<<arr[i][r]<<" ";
r--;
}
else if(dir==2) //printing from right to left
{
for(i=r;i>=l;i--)
cout<<arr[b][i]<<" ";
b--;
}
else if(dir==3) //printing from bottom to top
{
for(i=b;i>=t;i--)
cout<<arr[i][l]<<" ";
l++;
}
dir = (dir+1)%4; //changing the direction each time
}
}