Write a c program to print the elements of a 2D array or matrix in spiral order. for example look at the below matrix

spiral

The output should be 1 2 5 6 7 8 9 7 6 4 5 6.

Solution:

  • Print the elements of the top row from left to right and increment top.
  • Print the elements of right column from top to bottom and decrement right.
  • Print the elements of bottom tow from right to left and decrement bottom.
  • Print the elements of left column from bottom to top and increment left.

(The solution is taken from ,http://comproguide.blogspot.in/2013/11/printing-matrix-in-spiral-order.html, if you are java    programer you can get java code from given link)

Now let implement these steps in c:

#include<stdio.h>

#define r 3
#define c 4

void SpiralElements (int arr[][c], int row, int col);

int
main ()
{

  int m[][4] = {
  {1, 2, 5, 6},
  {4, 5, 6, 7},
  {6, 7, 9, 8}
  };
  // The output should be
  // 1 2 5 6 7 8 9 7 6 4 5 6  
   printf ("The spiral elements are:\n");

  /*call printSpiralElements */
  SpiralElements (m, r, c);
  return 0;
}

void
SpiralElements (int arr[][c], int row, int col)
{

  int top = 0;            // top index
  int bottom = row - 1;        // 3- 1 = 2
  int left = 0;
  int right = col - 1;        // 4 -1 = 3
  int dir=0;
  while(top <= bottom && left <= right)
  {
     int i=0;
     if( dir== 0)
     {
       for(i=0;i<=right;i++)
       printf("%d ",arr[top][i]);
       top++;
       dir=1;
     }
     else if( dir== 1)
     {
         for(i=top; i<=bottom; i++)
     {
             printf("%d ", arr[i][right]);
      }
         dir=2;
         right--;
     }

     else if( dir == 2)
     {
           for(i=right; i>=left;i--)
       printf("%d ", arr[right][i]);
      bottom--;
      dir=3;
     }
     else
     {
         for(i=bottom;i>top;i--)
     printf("%d ",arr[i][left]);
      left++;
      dir=0;
     }
     i=0;
  }
  printf("\n");
}

 



Related Contents to follow