C program for printing a matrix in spiral order, Exercises of Computer Networks

This c program implements a function to print a square matrix in spiral order. The program takes the number of test cases and the dimensions of the matrix as input for each test case. It then uses three pointers to traverse the matrix in a spiral pattern and prints the elements as they are visited.

Typology: Exercises

2018/2019

Uploaded on 11/18/2019

digital-krishna
digital-krishna 🇮🇳

1 document

1 / 2

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
#include <stdio.h>
int main(void) {
int t;
int m,n,i,l,top,r,b,count,j;
int a[100][100];
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
l=0;
top=0;
r=n-1;
b=m-1;
count=0;
while(1)
{
for(i=top;i<=r;i++)
{
printf("%d ",a[top][i]);
count++;
}
for(i=top+1;i<=b;i++)
{
printf("%d ",a[i][r]);
pf2

Partial preview of the text

Download C program for printing a matrix in spiral order and more Exercises Computer Networks in PDF only on Docsity!

#include <stdio.h>

int main(void) { int t; int m,n,i,l,top,r,b,count,j; int a[100][100]; scanf("%d",&t); while(t--) { scanf("%d%d",&m,&n); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); l=0; top=0; r=n-1; b=m-1; count=0; while(1) { for(i=top;i<=r;i++) { printf("%d ",a[top][i]); count++;

} for(i=top+1;i<=b;i++) { printf("%d ",a[i][r]);

count++;

for(i=r-1;i>=l;i--) { printf("%d ",a[b][i]); count++; } for(i=b-1;i>top;i--) { printf("%d ",a[i][l]); count++; } if(count==m*n) break; top++; r--; b--; l++;

}

return 0; }