Trouble With Nested For Loops

Is whats in that little picture your question? Can you copy and paste that into the post here so it can be easier to read? :wink:

I thought that if you click on the picture it will come up full size - it does for me on my iMac. But here is my letter -

for (var col = 0; col < 10; col++) 
    for (var row = 0; row < 15; row++) {
        rect(col*20, row*20, 20, 20);

so I don’t get how the code above gives us a 10 X 15 grid which is what it is supposed to do. So with the first run we have col = 0 and row = 0 which gives us a small rectangle at 0,0 - then both column and row increment to 1 which gives us another rectangle at 20,20 - another increment in the 2 variables to 2 and you get a rectangle at 40,40 and so on which gives us the above pattern.
The final value for var col = 9 which places a rectangle at 180,180 and then the
‘’ for (var row = 0; row < 15; row++) ‘’
runs from 10 - 14 which will place 5 more rectangles at the bottom of the last rectangle on the R.
At least this is the way that I see the code executing but obviously my thinking is wrong since this codes for a 10 X 15 grid. So can someone explain how this code executes since I am missing something here.

I think you’re mixing up the size and position arguments. The first 2 arguments, col*20 and row*20 are the position while the 20, 20 are the size. So each rectangle should be the same size, just changing in position.

The way the loops work is the outer loop (using col) runs from left to right, supplying the x value while the inner loop (using row) runs top to bottom supplying the y. For each iteration of the outer loop a single column is drawn by the inner loop as it goes through each row top to bottom drawing squares. This expands left to right with each iteration drawing columns of squares until 15 columns are made.

OK - I follow your explanation - I think. So when the column loop runs once, the row loop runs 15 times and then the sequence repeats with the second column etc., etc. ? That is not how I pictured events at all so thanks for setting me straight on that - your explanation makes sense of the process.

1 Like


1 Like