Drawing with Loops explainer

The aim of this puzzle: To draw 5 blue boxes using a classic for loop.

Walkthrough of the solution: The code view starts with a classic for loop:

for (var i = 0;  i < 3; i = i + 1) {

A classic for loop is made of three main parts. For example, in the code above, var i = 0 is the first part, declaring the looping variable i and assigning it the starting value of 0. i < 3 is the second part and states that the loop should keep looping while i is less than 3. The third and final part is i = i + 1, which is the increment, increasing the value of i by one each loop.

So in the first iteration of the loop a box is drawn since i is equal to 0 (which is less than three). At the end of this first loop i is incremented by 1, so i is equal to 1 at the start of the second iteration of the loop. Since i is still less than 3 another box is drawn, then i is increased again to 2. In the third iteration of the loop another box is drawn, then i is increased to 3. Since i is now 3, which is not less than 3, a 4th loop never happens and a 4th box is not drawn.

In this puzzle, 5 boxes should be drawn rather than 3, so i < 3 should be updated to be i < 5.

Sample code solution:
(Tap below to reveal)

for (var i = 0; i < 5; i = i + 1) {

JavaScript Concepts: Calling Functions, Classic For Loop, Variable Declarations
Grasshopper Concepts: drawBox()

But How var i is related to drawBox(‘blue’)

Hey there,

The for loop first initializes a variable named i, and gives it the value 0. That’s what var i = 0 is doing.

The for loop is then told to loop over and over as long as i < 5 is true.

The for loop will run the code inside its code block, and at the end of each loop, i = i + 1 will add 1 to i.

Altogether, it looks like this:

  1. Create a variable named i, set its value to 0
  2. Check if 0 is less than 5. It is.
  3. Run drawBox('blue')
  4. Increase i by 1
  5. Check if 1 is less than 5. It is.
  6. Run drawBox('blue')
  7. Increase i by 1
  8. Check if 2 is less than 5. It is.
  9. Run drawBox('blue')
  10. Increase i by 1
  11. Check if 3 is less than 5. It is.
  12. Run drawBox('blue')
  13. Increase i by 1
  14. Check if 4 is less than 5. It is.
  15. Run drawBox('blue')
  16. Increase i by 1
  17. Check if 5 is less than 5. It is not.
  18. Exit loop

Hope this helps!


THANK YOU , Now I got it