Hi friends,
Input matrix 4x4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
and the output of the program is ,
1 → 2 → 3 → 4
↓
5 → 6 → 7 8
↑ ↓ ↓
9 10 ←11 12
↑ ↓
13←14←15←16
Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
/*
Print Matrix in Spiral Order
Created by: Pirate
*/
#include<stdio.h>
#include<conio.h>
int main()
{
int a[100][100],i=0,j,k,r,c,i1=0,j1=1,p,count=0;
printf("Enter the size of matrix\t");
scanf("%d%d",&r,&c);
printf("Enter the %dX%d matrix",r,c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
}
p=c*r-1;
j=0;
while(1)
{
for(i=i1;i<c;i++)
{
printf("%d ",a[j][i]);
count++;
}
for(j=j1;j<r;j++)
{
printf("%d ",a[j][i-1]);
count++;
}
for(i=r-2;i>=i1;i--)
{
printf("%d ",a[j-1][i]);
count++;
}
if(count>p-1)
break;
for(i=j-2;i>i1;i--)
{
printf("%d ",a[i][i1]);
count++;
}
i1++;
j1++;
c--;
r--;
p--;
j=i1;
}
getch();
return 0;
}
Output:
Today I'm here with a new program that is print elements of a matrix in spiral order. We have to start from the element in the 0th row and 0th column in the matrix and proceed in a spiral order as shown below.
Input matrix 4x4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
and the output of the program is ,
1 → 2 → 3 → 4
↓
5 → 6 → 7 8
↑ ↓ ↓
9 10 ←11 12
↑ ↓
13←14←15←16
Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
/*
Print Matrix in Spiral Order
Created by: Pirate
*/
#include<stdio.h>
#include<conio.h>
int main()
{
int a[100][100],i=0,j,k,r,c,i1=0,j1=1,p,count=0;
printf("Enter the size of matrix\t");
scanf("%d%d",&r,&c);
printf("Enter the %dX%d matrix",r,c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
}
p=c*r-1;
j=0;
while(1)
{
for(i=i1;i<c;i++)
{
printf("%d ",a[j][i]);
count++;
}
for(j=j1;j<r;j++)
{
printf("%d ",a[j][i-1]);
count++;
}
for(i=r-2;i>=i1;i--)
{
printf("%d ",a[j-1][i]);
count++;
}
if(count>p-1)
break;
for(i=j-2;i>i1;i--)
{
printf("%d ",a[i][i1]);
count++;
}
i1++;
j1++;
c--;
r--;
p--;
j=i1;
}
getch();
return 0;
}
Output:
Enjoy :)
This comment has been removed by a blog administrator.
ReplyDeletethanks, its what i'm looking for.
ReplyDeletewelcome :)
Delete