# Thread: Printing 2-dimensional array spirally

1. ## Printing 2-dimensional array spirally

Hello,

Following code prints the 2-dimensional array spirally. Can anybody have better version or other ideas? Especially in highlighted areas.

Currently botton right element prints twice....

Code:
```# include<stdio.h>

void printElement(int i,int j,int maxCol,int maxRow);

int a[4][4] =  {
{1,2,3,11},
{4,5,6,12},
{7,8,9,13},
{14,15,16,17},
};

void main()
{
int maxCol = sizeof(a[0])/sizeof(a[0][0])-1;
int maxRow = sizeof(a)/sizeof(a[0])-1;
int i = 0;
int j = 0;

while ( (i < maxRow) && (j < maxCol) )
{
printElement(i,j,maxCol,maxRow);
i++;j++;
maxCol--;
maxRow--;
}
if ( (i == maxRow) && (j == maxCol) )
printf("%d\t",a[j][i]);
}

void printElement(int i,int j,int maxCol,int maxRow)
{
printf("%d\t",a[i][j]);

if ( j < maxCol )
{
j++;
printElement(i,j,maxCol,maxRow);
printf("%d\t",a[j][i]);
return;
}
if ( i < maxRow )
{
i++;
//		if ( i == maxRow )
//	                       return;
printElement(i,j,maxCol,maxRow);
printf("%d\t",a[j][i]);
return;
}
else
return;
}```

2. im not sure what you mean by 'spirally'
but i compiled this program and i dont really see any pattern at all

3. With above program, it should print

1,2,3,11,12,13,17,16,15,14,7,4,5,6,9,8

Let me know, if you can provide better solution....

4. Here's a fun one:
Code:
```#include <stdio.h>
#define YSIZE 4
#define XSIZE 4
int main( void )
{
int yadder = 0, ycoord = 0, yhsize = YSIZE-1, ylsize = 1,
xadder = 1, xcoord = 0, xhsize = XSIZE-1, xlsize = 0,
printed = 0;
int array[YSIZE][XSIZE] =
{
{  1,  2,  3,  4 },
{ 12, 13, 14,  5 },
{ 11, 16, 15,  6 },
{ 10,  9,  8,  7 },
};

for( printed = 0; printed < YSIZE * XSIZE; printed++, xcoord += xadder, ycoord += yadder )
{
printf("%d ", array[ycoord][xcoord] );
if( xadder > 0 && xcoord >= xhsize )
{
xhsize--;
}
else
if( xadder < 0 && xcoord <= xlsize )
{
xlsize++;
}
else
if( yadder > 0 && ycoord >= yhsize )
{
yhsize--;
}
else
if( yadder < 0 && ycoord <= ylsize )
{
ylsize++;
}
}
return 0;
}```
I'll let you decide if it's a "better solution".

Moved initialization from for for the sake of forum width, and other minor width-friendly editing to variable initializations.
[/edit]

Quzah.

5. > void main()
I'm sure you said this wasn't going to happen again in some previous post....

6. It was in this post where he said he wouldn't use it anymore.