1 Replies - 2303 Views - Last Post: 26 March 2009 - 08:12 PM Rate Topic: -----

#1 priya_lorha  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 78
  • Joined: 02-August 08

Spiral array, Icannot figure where the error is

Posted 26 March 2009 - 07:50 PM

Required Output


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


Is This A Good Question/Topic? 0
  • +

Replies To: Spiral array, Icannot figure where the error is

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8346
  • View blog
  • Posts: 31,908
  • Joined: 06-March 08

Re: Spiral array, Icannot figure where the error is

Posted 26 March 2009 - 08:12 PM

For Christ sake (or what ever is the God you respect) have meaningfull variable names
what are i,j,... OK loop variables
but c, m, n. s ???

And may be some comments ? You won't be able to read you back in 2 days
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1