Spiral code for java using recursion

Asked By 0 points N/A Posted on -
qa-featured

Can anyone write me spiral code for java using recursion? I don't understand this.. please help

 

SHARE
Answered By 0 points N/A #90006

Spiral code for java using recursion

qa-featured

I would have helped you a lot if it would have been in C++. Because in java, it is very difficult sometimes to handle the graphics. Anyhow I am pasting down a code which might help you to draw the required spiral that you are asking.

class spiral_matrix
{
public static void main()
{
int m[][] = new int [4][4];
int n=1, s=4, c=1, i=0, j=0;
while(n>=1)
{ 
do
{
m[i][j] = c++;
n++;
j++;
}
while(n<s);
n =  0;
do
{
m[i][j] = c++;
n++;
i++;
} 
while(n<s-1);
n = 0;
do
{
m[i][j]=c++;
n++;
j--;
}
while(n<s-1);
n = -1;
do
{
m[i][j] = c++;
n++;
}
while(n<s-2);
n = n - 2;
}
for(i=0; i<s; i++)
{
for(j=0; j<s; j++)
{
System.out.print(m[i][j] + " ");
}
System.out.println();
}
}
}

Note that you can change the iterations of the loops to as much spiral rings as you want in your drawing.
Also it also might be possible that this code will not run on your machine due to obvious machine dependent variables and paths.

Also do keep in mind to use your own logic as well if it don’t get you the required output.


 

Login/Register to Answer

Related Questions