WEEK: 8
Active: February 28th - March 6th
Work Due: March 7th @ 9:00AM

for Loops

To eloquently accomplish the problem on the last page, we need an eloquent control structure to build our control flow.

The name of this new control structure is for loop.


Loops are not new to you. You have been working with loops since we started animating. The draw() function is a loop. When a sketch starts p5 calls the draw() function. When the draw() function is done, p5 calls it again, and again, and again….. till we close the program. By updating variables within the draw loop, we are able to move things around the screen.

The for loop that you are about to learn is similar in some ways, and different in others from the draw() function.

  1. Whenever the draw() function is called, a ‘frame’ occurs. However, we can have multiple loops occur, using a for loop in a single frame.
  2. The for loop needs to run a finite number of times, unlike the draw() function. Therefor, we need to tell the computer when to stop executing a for loop.

Loops in Program Flow

In general, loops in code, instruct the computer to run some series of statements, encapsulated in a function block, some number of times.

Loop Program Flow Example

That loop will continue executing until told to stop. Thereby repeating some number of instructions, some number of times, in sequence.

Writing for Loops

Basic for loops in JavaScript (the kind we are about to learn) require 3 things to work;

  1. The definition of a Number variable.
  2. A conditional statement to evaluate when to stop running the for loop.
  3. A specification for how to update the defined Number variable.

Unlike almost every other function in JavaScript, these three requirements are separated by semicolons (;), instead of commas. (You will just need to remember that.) Written in pseudo-code, these parameters are passed to a for loop in the following way.

for( numberVariable; conditionalStatement; incrementDetails ) {
    // function block
    // loop statements go in here!
}

As you can see, each of the required pieces of data are passed into the for loop’s parenthesis, as you would normally do. However, notice that semicolons are used to separate each parameter.

Number Variable

Now, let’s talk about each of these parameters. The first statement passed to the for loop is a Number variable definition and initialization.

This is no different then how you normally define and initialize a number variable. This will typically take the form of something like;

let i=0;

When passed as the first statement to a for loop, it will look like the following…

for( let i=0; )

…then the computer, at the start of the for loop will create and initialize a variable, for use within the for loop.

Conditional Statement

The second statement passed to a for loop is a conditional statement that is evaluated at the beginning of each loop iteration.

  • If the conditional statement returns true then the for loop executes the statements within the function block.
  • If the conditional statement instead returns false, the computer skips the function block, exits the for loop, and goes on to execute the rest of the program.

The conditional statement in a for loop will look like the types of conditional statements you learned how to compose last week. Typically though, this conditional statement will test the variable you defined in the for loop against some value. Usually, this will be a Number value representing the number of times the loop is to execute.

For example, in the following conditional statement, the loop would execute, as long as it is less than (<) 2.

i < 2;

This statement is passed second to the for loop and would look like;

for( let i=0; i < 2; )

Update Statement

The final statement passed to a for loop is the update statement. The update statement tells the computer how to update the variable defined earlier on.

This statement is executed after each iteration of the for loop.

If you wanted to create a for loop that executed 2 times, still utilizing the example we started above, you would tell the loop to increment the variable by ‘1’ every time.

This may look like;

i++

Within the for loop, this would look like;

for( vasr i=0; i < 2; i++ ) {
    // do something
}

Again, the update statement will occur after the execution of the function block.

In the example we have just built, the computer would;

  1. Define and initialize a variable, i, to the value of 0.
  2. Test whether the value of i is less than 2.
  3. Since this condition test would return true, the function block would be executed.
  4. After successful execution of the function block, the for loop would then execute the update statement, i++, thereby changing the value of i (originally 0) to 1.
  5. The for loop would then execute the conditional statement again, thereby testing whether to keep going. Since i=1 is still less than 2, the for loop would execute the function block again.
  6. After successful execution of the function block a second time, the for loop would then execute the update statement again, i++, thereby changing the value of i to 2.
  7. The for loop would then execute the conditional statement again, thereby testing whether to keep going. Since i is currently equal to 2, the conditional statement would return false. The for loop would therefor exit, and not execute the function block again.

In Action

Let’s refactor our example from the last page, where we created 10 ellipses, with this new for loop capability.

Instead of writing out the code to create an ellipse 10 times, we will instead write a for loop that will execute 10 times, thereby drawing 10 ellipses. To do this, the for loop will need to;

  1. Define and initialize a variable (i) to the Number 0.
  2. Test whether this variable (i) is less than the 10. (The number of times we want to execute the loop)
  3. Increment the variable (i) every loop.

This would look like;

for( let i=0; i < 10; i++ ){
    //draw circles
}

Note how we test whether i is “less than” 10, and not “less than or equal” to 10. Since we start at 0, if we ran through i equalling 10, we would actually execute the loop 11 times.

  • i=0 first time
  • i=1 second time
  • i=2 third time
  • i=3 forth time
  • i=4 fifth time
  • i=5 sixth time
  • i=6 seventh time
  • i=7 eighth time
  • i=8 ninth time
  • i=9 tenth time

Using i

It is very common to the use the variable defined in a for loop within the loop’s function block. Typically this variable is used make the code “do something” in relation to the loop’s “iteration number”.

So, in our refactor example, we are trying to draw 10 ellipses, across the canvas’ width. In the procedural example in which we wrote each line of code, this was accomplished by hard coding the X position of each ellipse to be a ratio of the canvas width.

let pos_x = width * 1/10;

Where, in the above code, ‘1/10’ is the ratio of the ellipse to canvas width. In this specific case, one-tenth of the canvas’ width.

Using a for loop we can replace the number ‘1’ with the variable i. Thereby, changing this ratio with each loop iteration.

Our for loop code might look like the following;

for( let i=0; i<10; i++ ) {
    // find the x_pos
    pos_x = width * i/10;
    // draw an ellipse
    ellipse( pos_x, pos_y, d );
}

The above code will iterate the for loop ten times. Each iteration, the variable pos_x will be reassigned to a value that is in relation to the width of the canvas and the for loop’s variable i. Then the for loop will draw the ellipse, using the updated pos_x variable.

Altogether, our refactored example might look like;

[ Code Download ] [ View on GitHub ] [ Live Example ]

Notice: The above example now has a “Run” button in the top left. This allows you to explicitly tell the compiler when to execute the code and show you the results. This feature has been added so that you do not accidentally create infinite loops that lock up your browser.


Previous section:
Next section: