java - Can someone explain to me why this nested loop function print this way? -
so here code runs:
public static void main(string[] args) { (int i=1; i<=6; i++) { (int j=1; j<=i; j++) system.out.print("*"); system.out.print("-"); } } why print
*-**-***-****-*****-******-
instead of
* _ ** __ *** ___ **** ____ *****_____******______
system.out.print("-"); not inside inner loop. therefore it's printed once each iteration of outer loop.
this becomes clearer when indent code :
for (int i=1; i<=6; i++) { (int j=1; j<=i; j++) system.out.print("*"); system.out.print("-"); } even if inside inner loop (by adding curly braces), you'd still not output expected, since you'll 1 - after each *.
in order output expected, need 2 inner loops :
for (int i=1; i<=6; i++) { (int j=1; j<=i; j++) system.out.print("*"); (int j=1; j<=i; j++) system.out.print("-"); }
Comments
Post a Comment