Search code examples
javaprocessing

I don't understand why my nested for loop works


The objective is to draw a number of squares on a canvas depending on the defined number of rows and columns:

int squareSize = 20;
int distance = squareSize + 10;
int numberofRows = 8;
int numberofColumns = 10;

for (int rows = 0; rows < numberofRows; rows++)
{

    for(int columns = 0; columns < numberofColumns ; columns++)
     {
        square(30 + (distance * rows), 30 + (distance * columns), squareSize);

     }
}

I'm confused as of to how the program still executes the code in the inner for() loop when the number of rows is lower than the number of columns. I thought I'd have a problem since it was to my understanding that the inner loop would only be read and executed only and only if the outer loop proved to be true (so in this case, the program would stop working when the number of rows reached 8.)

...Yet the program still gives the expected results when I insert a lower number of rows than of columns. Why is that? EDIT: English isn't my first language so I made a very stupid mistake in my question. Obviously my question is how the code is executed when the number of rows is lower than the number of columns. I've edited the post accordingly.


Solution

  • You need to read slowly your code. As said, the two loops are detached one from each other. Also replacing the variables with their values might be useful to understand:

    for (int i= 0; i< 8; i++)
    {
    
        for(int j = 0; j< 10; j++)
         {
            square(30 + (30* i), 30 + (30* j), 20);
    
         }
    

    }

    As you can see the square function first is called with i=0 j=0 then it's:

    square(30,30,20).
    Then i=0, j=1
    square(30,60,20)
    Then i=0 j=2
    square(30,90,20).
    ...
    i=0 j=10
    square(30,330,20)
    Then the inner for reached the maximum and then you come again to your outer loop and add one to i. 
    i=1 j=0 
    square(60,30,20)
    i=1 j=1
    square(60,60,20)
    ...
    i=1 j=10
    square(60,330,20)
    ...
    

    keep doing this exercise until the maximum value of i=8 and j=10.

    square(240,330,20)
    

    All these square functions will be called in that specific order with those arguments. If you want further insight please tell what this square function does.

    Regards.