1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Output generated
1 2 3 4
18 17 0 5
12 0 0 6
14 15 9 8
class spiral
{static void main(int n)
{
int [][]matrix=new int[n][n];
int side=n,i=0,j=0,counter=1; // i and j are the loop variables
// stores the element
while(side>1)
{ for(j=0;j<side;j++)
{matrix[i][j]=counter++;}
j--;
for(i=1;i<side;i++)
{matrix[i][j]=counter++;}
i--;
for(j=(side-1);j>=0;j--){
matrix[i][j]=counter++;}j++;
for(i=(side-2);i>0;i--)
{matrix[i][j]=counter++;}i++;
i++;j++;
side=side-2;// size is reduced
i++;j++;
}
//Print the elements
for(i=0;i<n;i++){
for(j=0;j<n;j++){
System.out.print(matrix[i][j]+ " ");}
System.out.println();
}
}
}
Any modification results in array index out of bound error
This post has been edited by priya_lorha: 27 March 2009 - 05:36 AM

New Topic/Question
Reply




MultiQuote



|