Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

22
Apr

Printing array spirally - recursive routine

Related Blog Items

I have written a program for printing array in spiral order (iterative version) in an earlier post. Here, in this post let us see how we can make this algorithm even simpler using recursive routine.

the logic behind this routine is explained in the below diagram.

printing_array spirally recursive way

in C, array is stored in row major order, we can get address of any element (arr[row][column]) using

arr + (row * sizeof(elementType)*MAX_COLS) + column

so we are taking advantage of this layout (row major order), and printing rings by rings by updating the base address and num of columns, and num of rows.

here is the routine…

#define MAX_COLS 20
 
int print_array_spirally(int arr[][MAX_COLS], int num_rows, int num_cols)
{
  int i;
 
  if ((num_rows<=0) || (num_cols<=0))
  {
    return 0;
  }
 
  if (num_rows < 2 || num_cols < 2)
  {
    //deal with 1xN, Nx1 arrays
    for(i=0; (num_cols-1) && (i<num_cols); i++)
    {
      printf("%d ", arr[0][i]);
    }
 
    for(i=0; (num_rows-1) && (i<num_rows); i++)
    {
      printf("%d ", arr[i][0]);
    }
    return 0;
  }
 
  for(i=0; i<num_cols; i++)
  {
    printf("%d ", arr[0][i]);
  }
 
  for(i=0; i<num_rows-1; i++)
  {
    //exclude top column number as it is printed part of row
    printf("%d ", arr[i+1][num_cols-1]);
  }
 
  for(i=1; i<=num_cols-1; i++)
  {
    //exclude bottom right number as it is printed part of column
    printf("%d ", arr[num_rows-1][num_cols-i-1]);
  }
 
  for(i=1; i<=num_rows-2; i++)
  {
    //exclude bottom left and top, left numbers as they are already printed
    printf("%d ", arr[num_rows-i-1][0]);
  }
 
  //array stored in row-major order
  print_array_spirally((char *)arr+(sizeof(int)*(1+MAX_COLS)), 
                       num_rows-2, 
                       num_cols-2);
 
  return 0;
}
 
#ifdef TEST
int main()
{
  int arr[][MAX_COLS] = {{1, 2, 3, 10, 17}, {4, 5, 6, 11, 18}, {7, 8, 9, 12, 19}, {13, 14, 15, 16, 20}};
 
  print_array_spirally(arr, 4, 5);
}
#endif

download full [source code]

comments are always welcome…

Popularity: 16%

You need to log on to convert this article into PDF


Related Blog Items

2 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