Search code examples
javafor-loopnested-loops

Nested For Loop - Why with the code written like this, do I get more asterix than println?


int n = 10;

for(int i = 0; i < n; i++)
  {
      for(int j = 0; j <= i; j++)
      System.out.print("*");
      System.out.println();
  }

Question says it really, was struggling with this task a bit, and I tried it this way and it works, but I cant quite figure out why, written like this, it looks like there would be the same amount of println statements as asterix (*) symbols. Which would obviously not make the desired triangle (It would just make a line as long as n). So the only way I can see why this works is by picturing another brace for the initial for loop with the println statement. I presume it is something I have forgotten about how the for loop executes its code. But Could anyone shed some light on this for me?

So is the code not better written like this?

for(int i = 0; i < n; i++) {
   for (int j = 0; j <= i; j++) {            
          System.out.print("*");
        }
        System.out.println();
   }

Solution

  • because inner loop's body is just one statement

    for(int j = 0; j <= i; j++)
          System.out.print("*");
    

    without brackets around

    change it to

     for(int j = 0; j <= i; j++) { 
          System.out.print("*");
          System.out.println();
     }
    

    or even you don't need second statement this way

     for(int j = 0; j <= i; j++) { 
          System.out.println("*");
     }