Lesson 4.1

Repeating code with while and for loops

Watch: while and for Loops- p5.js tutorial

Video for 4.1:

Up until now we have had only one way to repeat code – by placing it in the draw() where it is called again and again.

For example, if we wanted to make many circles starting at x = 0 and covering the canvas horizontally, we could write

We have control over the initial value of x, and could extend our control by limiting how long we increment x with some conditional statement. For example, we could start at x = 50 and stop at x = 200 with the following code.

This works, but it relies on the looping nature of the draw() function.

While and for loops allow us to repeat code without relying on the draw() function.

The while loop has the same syntax as an if conditional statement.

Means something very similar to

They both mean, "if a condition is met, namely that x < 250, execute the block of code in curly brackets. The difference is that the while statement does not rely on the looping function to repeat the code.

How would we draw a set of circles using the while loop?

Since the while loop does not rely on the looping feature of the draw() function, we could place the code in setup() and achieve the same result.

Example 4.1.1: Drawing 4 circles with a while loop

Example 4.1.1

How does a while loop work?

It has 4 parts.

Statement 1:
- It starts with an initial value for some variable that will be incremented.
- For example, x = 50
Statement 2:
- It states the condition that must be met to keep incrementing the variable.
- For example, x < 250
Statement 3:
- It states by how much the variable is to be incremented.
- For example, x = x + 50
Statement 4:
- It gives some block of code to be executed for each value of the variable.
- For example, ellipse(x,200,20,20)

The for loop works the same way.

It also has the same 4 parts, but they are written in a different order. The syntax is

Here is the previous code using a for loop.

It is in general better to make variables local as compared to global to avoid unintentional assignments. Here is the for loop with the variable x as part of the loop and local to the draw() function.

Exercise 4.1a: Using only setup() , (without using the draw() to loop) place 500 small circles randomly on the canvas.

Exercise 4.1a

Exercise 4.1b: Using only setup() , (without using the draw() to loop) place a grid with lines 10 pixels apart on the canvas.

Exercise 4.1b

Exercise 4.1b help

Exercise 4.1c: Using only setup() , (without using the draw() to loop)place 12 circles spaced like the numbers on a clock, from 1-12, on the canvas.

Exercise 4.1c

Exercise 4.1c help

Exercise 4.1d: Using only setup() , (without using the draw() to loop) create the following on the canvas.

Exercise 4.1d