Wednesday, 15 June 2011

java - pyramid numbers in alternative reverse order -



java - pyramid numbers in alternative reverse order -

i asked write code below structure:

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

and tried below code, works, yet i'm wondering if there improve approach this:

public static void main(string[] args) { int no_of_rows=5; int c=0; for(int i=1;i<=no_of_rows;i++){ for(int k=i;k<no_of_rows;k++){ system.out.print(" "); } if(i%2!=0){ for(int j=0;j<i;j++){ c++; system.out.print(c +" "); } } else{ int a[] = new int [i+1]; for(int j=0;j<i;j++){ c++; a[j]=c; } for(int j=i-1;j>=0;j--){ system.out.print(a[j]+" "); } } system.out.println(""); } }

is there improve implementation or doing right?

i think improvement remove array in block:

else{ int a[] = new int [i+1]; for(int j=0;j<i;j++){ c++; a[j]=c; } for(int j=i-1;j>=0;j--){ system.out.print(a[j]+" "); } }

we can calculate values used in reverse order without need of additional array:

c += i;//update c for(int j = 0; j < ; j++){ system.out.print((c - j) + " " ); }

java

No comments:

Post a Comment