This Program prints the numbers in given array(Row-Major Order)
in Spiral order.
Ex: Order Is 3*4
11 12 13 14
15 16 17 18
19 20 21 22
23 24 25 26
Spiral Order Of Matrix is 11 12 13 14 18 22 26 25 24 23 19 15 16 17 21 20
This Program prints the numbers in given array(Row-Major Order)
in Spiral order.
Ex: Order Is 3*4
11 12 13 14
15 16 17 18
19 20 21 22
23 24 25 26
Spiral Order Of Matrix is 11 12 13 14 18 22 26 25 24 23 19 15 16 17 21 20
#include<stdio.h>
main()
{
int a[20][20],i,j,n,m,p,q,k=0;
printf("\n Enter Order Of matrix");
scanf("%d%d",&m,&n);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
p=m;
q=n;
i=j=1;
while(k<p*q)
{
for(;j<=n&&k<p*q;j++)
{
printf("%d ",a[i][j]);
k++;
}
j--;
i++;
for(;i<=m && k<p*q;i++)
{
printf("%d ",a[i][j]);
k++;
}
i--;
j--;
for(;j>=i-m+1 && k<p*q;j--)
{
printf("%d ",a[i][j]);
k++;
}
j++;
i--;
for(;i>1 && k<p*q;i--)
{
printf("%d ",a[i][j]);
k++;
}
if(k<p*q)
{
j++;
i++;
n--;
m--;
}
}
}
thank you
Beautiful man
You need a space between the variables here:scanf("%d%d",&m,&n);
should be this:scanf("%d %d",&m,&n);
otherwise it is not clear that the user needs to put a white space between the two values. You can mitigate that by specifying that in the instructions. IE,
"Enter order of matrix, as in 'x y' where x is the width and y is the height". Once they enter the order, then output something like this: "Now, enter the values of the matrix. These will be entered left-to-right, top-to-bottom."
Next, these lines should be bracketed in order to avoid "sophomoric" errors:
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
/* Should be this */
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
My final critique is that your code should be more symbolically clear in order for others to read and understand the intention of the code more clearly. IE, instead of variables m (assume height) and n (width), use the terms "height" and "width". Remember, "correct != good || clear"... :-)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.