java nested for loops to get numbers triangle -



java nested for loops to get numbers triangle -

this question has reply here:

java - creating triangle numbers using nested for-loops [closed] 2 answers

my output should in image 1, output looks in image 2.

i not suppose print out ... there have print out same thing 32 64. int have far, got half of triangle correct. don't know how reverse though.

k = 1; int j; int l = 1; for(int i=1; <= 8; i++){ for(j=8; j>i; j--){ system.out.print(" "); } for(j=1; j<=k; j=j*2){ system.out.print(j + " "); } (j = 1; j<k; j=j*2) { system.out.print(j + " "); } k = k * 2; system.out.println(); } } }

your problem is, in 2nd loop, still go j=1 -> k. can k -> 1 loop reversed sequence.

also java has printf method, may want take look..

some illustration codes:

int rows = 8; (int r = 0; r <= rows; r++) { system.out.print(new string(new char[rows - r]).replace("\0", " ")); int c = 0; (int = 0; <= r; i++) system.out.printf("%s%s", 1<<i, r == 0? "\n" : " "); if (r > 0) (int = r-1; >= 0; i--) system.out.printf("%s%s", 1<<i, == 0? "\n" : " "); }

just adjust rows value like.

i did test rows=8, prints:

1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 16 8 4 2 1 1 2 4 8 16 32 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 256 128 64 32 16 8 4 2 1

java nested-loops

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -