spiral printing of a two dimensional array

#include <stdio.h>

void spiralPrint(int m, int n, int a[][n])
{

int i, k = 0, l = 0;

m--, n--;

/*
        k - min row
        m - max row
        l - min column
        n - max column

        i - iterator
    */

while(k <= m && l <= n){

for(i = l; i <= n; ++i) {
printf("%d ", a[k][i]);
}

k++;

for(i = k; i <= m; ++i) {
printf("%d ", a[i][n]);
}

n--;

if(m >= k) {

for(i = n; i >= l; --i) {
printf("%d ", a[m][i]);
}

m--;
}

for(i = m; i >= k; --i) {
printf("%d ", a[i][l]);
}

l++;
}


printf("\n");
}

int main()
{
printf("1, 2, 3, 4, 5, 6\n");
printf("7, 8, 9, 10, 11, 12\n");
printf("13, 14, 15, 16, 17, 18\n");
printf("19, 20, 21, 22, 23, 24\n");
printf("25, 26, 27, 28, 29, 30\n");
printf("35, 36, 37, 38, 39, 40\n\n");

int a[6][6] = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18},
{19, 20, 21, 22, 23, 24},
{25, 26, 27, 28, 29, 30},
{35, 36, 37, 38, 39, 40}
};

spiralPrint(6, 6, a);
}
Advertisements

2 thoughts on “spiral printing of a two dimensional array

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s