16
Feb
Printing array spirally - c program
Related Blog Items
- Printing array spirally - recursive routine
- Print In Reverse-Order
- Questions asked in various job interviews (in Programming)
- Printing linked List in Reverse without Reversing The List Actually
- Max Sum between two array indexes
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: 23%
You need to log on to convert this article into PDF
Related Blog Items - Printing array spirally - recursive routine
- Print In Reverse-Order
- Questions asked in various job interviews (in Programming)
- Printing linked List in Reverse without Reversing The List Actually
- Max Sum between two array indexes
Related Blog Items
- Printing array spirally - recursive routine
- Print In Reverse-Order
- Questions asked in various job interviews (in Programming)
- Printing linked List in Reverse without Reversing The List Actually
- Max Sum between two array indexes
[…] 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. […]
April 22nd, 2007 at 2:15 pm
good work dude
December 24th, 2007 at 3:40 pm
really wonderful program, your recursive routine for printing in spiral order is even amazing.
January 20th, 2008 at 5:57 pm