Two at a Time Explainer


#1

The aim of this puzzle: Edit the classic for loop to print every odd number under 10.
Walkthrough of the solution: A classic for loop is used to repeat a block of code a specific number of times. A classic for loop has 3 components separated by semicolons:

  1. A start condition that declares looping variable and gives it a value.
  2. A test that keeps the classic for loop running as long as the test is true.
  3. An update operation that changes the looping variable after each iteration (loop).

For example:

for (var i = 0; i < 10; i = 1 + 1) {
  print(i)
}
  1. var i = 0 sets up the looping variable i and gives it the value 0.
  2. i < 10 is the test. The classic for loop will run as long as i is less than 10.
  3. i = i + 1 updates the value of i after each iteration, adding 1 to the value each time.

In this puzzle, a classic for loop has been set up that sets i to 1 and counts up while i < 10 is true. This prints out the numbers 1 through 9.

To complete the puzzle, edit the classic for loop to update i by 2 after each iteration, rather than 1.

To do this, change i = i + 1 to i = i + 2.

Sample code solution:
(Tap below to reveal)

for (var i = 1; i < 10; i = i + 2) {
    print(i);
}

JavaScript Concepts: Code Block (for loop), Calling Functions, Variable Declaration, Identifiers, Loops
Grasshopper Concepts: print()


listed #2