//Program to print 2-D array in spiral order.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[10][10];
int m,n,t=0,b,l=0,r,dir=0,i,j;
cout<<"\nEnter order of matrix \n";
cout<<"\nNo. of rows = ";
cin>>m;
cout<<"\nNo. of columns = ";
cin>>n;
cout<<"\nEnter matrix\n\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cin>>a[i][j];
}
b=m-1;
r=n-1;
cout<<"\nArray Elements in spiral order is\n\n";
while(t<=b &&l<=r)
{
if(dir==0)
{
for(i=l;i<=r;i++)
cout<<" "<<a[t][i];
t++;
dir=1;
}
else
if(dir==1)
{
for(i=t;i<=b;i++)
cout<<" "<<a[i][r];
r--;
dir=2;
}
else
if(dir==2)
{
for(i=r;i>=l;i--)
cout<<" "<<a[b][i];
b--;
dir=3;
}
else
if(dir==3)
{
for(i=b;i>=t;i--)
cout<<" "<<a[i][l];
l++;
dir=0;
}
}
getch();
}
Output:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[10][10];
int m,n,t=0,b,l=0,r,dir=0,i,j;
cout<<"\nEnter order of matrix \n";
cout<<"\nNo. of rows = ";
cin>>m;
cout<<"\nNo. of columns = ";
cin>>n;
cout<<"\nEnter matrix\n\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cin>>a[i][j];
}
b=m-1;
r=n-1;
cout<<"\nArray Elements in spiral order is\n\n";
while(t<=b &&l<=r)
{
if(dir==0)
{
for(i=l;i<=r;i++)
cout<<" "<<a[t][i];
t++;
dir=1;
}
else
if(dir==1)
{
for(i=t;i<=b;i++)
cout<<" "<<a[i][r];
r--;
dir=2;
}
else
if(dir==2)
{
for(i=r;i>=l;i--)
cout<<" "<<a[b][i];
b--;
dir=3;
}
else
if(dir==3)
{
for(i=b;i>=t;i--)
cout<<" "<<a[i][l];
l++;
dir=0;
}
}
getch();
}
Output:
No comments:
Post a Comment