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()