print the elements of a matrix of order n x m, in the spiral order

example:

input matrix:
1     2     3
4     5     6
7     8     9
Output should be 1 2 3 6 9 8 7 4 5


c program to read the matrix elements and to print them in the spiral order.

Program:

#include<stdio.h>
#include<stdlib.h>
int main()
{
              int left,right,top,bottom;
              int n,m;
              int i,j;
              printf("enter n, m: ");
              scanf("%d%d",&n,&m);
              int a[n][m];
              printf("enter matrix elements\n");
              /*     loop for reading matrix elements    */
              for(i=0;i<=(n-1);i++)                  /* for every row   */
                    for(j=0;j<=m-1;j++)             /* for every column in a row   */
                          scanf("%d",&a[i][j]);     /*  read element    */
              left=0;
              top=0;
              right=m-1;
              bottom=n-1;
        /* print every element only once in spiral order  */
              while((left<=right)&&(bottom>=top))    
              {
                      for(i=left;i<=right;i++)
                      {
                       printf("%d",a[top][i]);                  /* print top row from left to right  */
                       }
                       top++;                                         /* after completing one top row    */
                       for(i=top;i<=bottom;i++)
                      {
                      printf("%d",a[i][right]);             /* print right column from top to bottom */
                      }
                      right--;                                       /* after completing one right column  */
                      if(bottom>=top)                         /* check for bottom>=top   */
                      {
                              for(i=right;i>=left;i--)
                              {
                              printf("%d",a[bottom][i]);    /* print bottom row from right to left  */
                              }
                              bottom--;                              /* after completing one bottom row    */
                              for(i=bottom;i>=top;i--)
                              {
                              printf("%d",a[i][left]);            /* print left column from bottom to top  */
                              }
                              left++;                                   /* after completing one left column  */
                      }
              }
              return 0;
}

Sample input 1:
enter n, m: 3 5
enter matrix elements
1    2    3    4    5
6    7    8    9   10
11  12 13  14   15
Output1:
1 2 3 4 5 10 15 14 13 12 11 6 7 8 9

No comments: