# Spiral array, Icannot figure where the error is

Page 1 of 1

## 1 Replies - 2558 Views - Last Post: 26 March 2009 - 08:12 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=95600&amp;s=e9fc8ed3c0c009c73888368549e2c108&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 priya_lorha

Reputation: 6
• Posts: 82
• 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

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

Reputation: 8378
• Posts: 31,956
• 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