spiral matrix for n*n order
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

. It is for printing a spiral matrix when n=5. It gave a correct output only for the elements on the sides.

view sourceprint?01 class spiral_matrix

02 {

03 public static void main()

04 {

05 int m[][] = new int [4][4];

06 int n=1, s=4, c=1, i=0, j=0;

07 while(n>=1)

08 {

09 do

10 {

11 m[j] = c++;

12 n++;

13 j++;

14 }

15 while(n<s);

16 n = 0;

17 do

18 {

19 m[j] = c++;

20 n++;

21 i++;

22 }

23 while(n<s-1);

24 n = 0;

25 do

26 {

27 m[j]=c++;

28 n++;

29 j--;

30 }

31 while(n<s-1);

32 n = -1;

33 do

34 {

35 m[j] = c++;

36 n++;

37 i--;

38 }

39 while(n<s-2);

40 n = n - 2;

41 }

42 for(i=0; i<s; i++)

43 {

44 for(j=0; j<s; j++)

45 {

46 System.out.print(m[j] + " ");

47 }

48 System.out.println();

49 }

50 }

51 }

can anyone help me with this for n*n order

1 2 3 4
5 8 9 10
6 11 13 14
7 12 15 16

Please use CODE tags.
Explain your problem clearly.

Your class should be defined properly, e.g.

class spiral_matrix{
  int N;
  int matrix_data[][];

  public sparse_matrix(){
    /*Constructor*/
  }
  public init_matrix(){
    /*initialize your matrix here*/
  }
  public static void main(String argv[]){
    /*...........*/
  }
/* other member methods*/
}

Actually, if I may suggest, the initialization should take place in the constructor. So when the user creates that object, the array would be initialized and not having to call any other methods.

We usually initialize things in the constructor. Of course the method init_matrix could be private and be called in the constructor.

Of course the issue here is that the code posted here doesn't make any sense

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.