Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

16
Feb

Printing array spirally - c program

Related Blog Items

Printing array in spiral order is not that tough as we think, if we properly maintain directions and positions of indexes
we are done, here is such simple program…

/*Printing array spirally for ex.

1    2    3    4

5    6    7    8

9    10   11  12

13   14   15   16

need to print the above matrix in 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 order (i.e. spirally) */

 
#include <stdio.h>
 
#define MAX_COLS 20
 
enum
{
  ARR_RIGHT,
  ARR_DOWN,
  ARR_LEFT,
  ARR_UP
};
 
int array_spiral_print(int arr[][MAX_COLS], int num_rows, int num_cols)
{
  int m = num_rows-1;  //num_rows
  int n = num_cols-1;  //num cols
  int m_begin = 0, n_begin = 0, m_end = m, n_end = n;
  int direction = ARR_RIGHT;
  int i,j;
 
  while((m_begin<m) && (m_end>0) && (n_begin<n) && (n_end>0))
  {
    switch(direction)
    {
    case ARR_RIGHT:
      for (j=n_begin; j<=n_end; j++)
      {
        printf("%d ", arr[m_begin][j]);
      }
      m_begin++;
      direction = ARR_DOWN;
      break;
    case ARR_DOWN:
      for (i=m_begin; i<=m_end; i++)
      {
        printf("%d ", arr[i][n_end]);
      }
      n_end- -;
      direction = ARR_LEFT;
      break;
    case ARR_LEFT:
      for (j=n_end; j>=n_begin; j- -)
      {
        printf("%d ", arr[m_end][j]);
      }
      m_end- -;
      direction = ARR_UP;
      break;
    case ARR_UP:
      for (i=m_end; i>=m_begin; i- -)
      {
        printf("%d ", arr[i][n_begin]);
      }
      n_begin++;
      direction = ARR_RIGHT;
 
      break;
    }
  }
 
  return 0;
}
 
#ifdef TEST
int main()
{
  int arr[][MAX_COLS] = {{1, 2, 3, 10}, {4, 5, 6, 11}, {7, 8, 9, 12}, {13, 14, 15, 16}};
  array_spiral_print(arr, 4, 4);
}
#endif

download [source code] for the above program which is a c file.

please let me know your comments….

Popularity: 25%

You need to log on to convert this article into PDF


Related Blog Items

3 Comments

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image