# Printing numbers in spiral shape

I need an algorithm for some program. I'll take some number (say 'n'), then i should print the numbers in spiral shape starting from square(n). Can any one pls help me..

Ex: if n=3, it should print like

9 8 7
2 1 6
3 4 5

#### Gerda Profile Answers by Gerda

• May 8th, 2008

One of possible solutions:

public class NumberSpiralShape {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

int n = 3, i, side = n, x=0, y=0;int tab [][]= new int [n][n];

i=n*n;

while(i>=1){for(int j=0; j<side; j++)

tab[x][y++] = i--;

x++;

y--;

if(i>=1){for(int j=0; j<side-1; j++)

tab[x++][y] = i--;

x--;

y--;

}

if(i>=1){for(int j=0; j<side-1; j++)

tab[x][y--] = i--;

x--;

y++;

}

if(i>=1){for(int j=0; j<side-2; j++)

tab[x--][y] = i--;

y++;

x++;

side=side-2;

}

}

//print

for(i=0; i<n; i++){

for(int j=0; j<n; j++)System.

out.print(tab[i][j] + " ");System.out.println("n");

}

}

}

#### datdo Profile Answers by datdo

• Jan 29th, 2009

//spiral
//by datdo
//translated C code
public class Spiral {

int n =3;
public static int SPIRALHEIGHT =  n;
public static int SPIRALWIDTH = n;

public static main(String[] args) {
int matrix[SPIRALWIDTH][SPIRALHEIGHT];
int c,r,rr, cc;
int a = 0;
cc = 0;
rr = 0;
for(c = 0; c < SPIRALHEIGHT; c++) {
for(r = 0; r < SPIRALWIDTH; r++) {
matrix[r][c] = 0;
}
}
c =-1;
r =-2;
while(a < SPIRALWIDTH * SPIRALHEIGHT) {
for(r+=2; r < SPIRALWIDTH -rr; r++) {
matrix[r][c+1] = a;
a++;
}
for(c+=2; c < SPIRALHEIGHT - cc; c++) {
matrix[r - 1][c] = a;
a++;
}
cc++;
for(r-=2; r > rr-1 ; r--) {
matrix[r][c - 1] = a;
a++;
}
for(c-=2; c > cc-1 ; c--) {
matrix[r+1][c] = a;
a++;
}
rr++;
}
for(c = 0; c < SPIRALHEIGHT; c++) {
for(r = 0; r < SPIRALWIDTH; r++) {
System.out.print("%3d ", matrix[r][c]);
}
System.out.print("n");
}
}