2-1 Conditional Loops

The Road Ahead

We’ve had a great start learning the basic features and syntax of p5.js but there is more we need to cover to have a complete foundation in programming concepts.  In this series of lessons, we’ll look at an important feature of any programming language: how to repeat code using a structure called a loop.  After that, we’ll talk about how to better organize our code using functions, objects, and classes, and how to use a special data structure called an array to make it easy to deal with many objects at once.  The final lesson is a special treat called recursion, stay tuned!

What is Iteration / Repetition?

As I mentioned in our very first lesson, every programming language needs to support 3 important features:

    1. Sequence: When a program is run, the statements in a function are executed in order, from top to bottom.
    2. Decision Making: Based on some condition, our program can run different { blocks } of code.  The technical term for decision-making in Computer Science is selection.
    3. Repetition (or “looping”): Our code runs a specific set of instructions over and over again until some condition or a specific number of repetitions have been achieved. The technical term for looping in Computer Science is iteration.

We have covered the first two features in p5.js and are now ready to tackle iteration (looping)!  We have covered the first two and are now ready to tackle iteration (looping)!  We have covered the first two and are now ready to tackle iteration (looping)!  See, loops are fun!

Why We Need Iteration

Consider the following example that draws a series of evenly spaced vertical lines:

You should see a pattern here.  Only the x-coordinates change for each line, but otherwise, they are essentially the same.  But what if we’d like to draw fewer or more lines automatically based on the canvas size?  We could cut, paste, and modify lines to do this, but loops are designed to avoid all of this manual work, shorten our code, and make it more flexible and efficient.

The while Loop

Several types of loops are supported by most programming languages, but the most essential and versatile one is called a while loop.  Any algorithm requiring a loop can be implemented using only the while loop.  In the next lesson, we’ll look at a handy alternative to the while loop called a for loop.  There is also a do..while loop, but it’s rarely useful once you’ve mastered the while and for loops so we won’t cover this one.

The best way to think about a while loop is like a repeating if statement.  Like an if statement, the while loop starts by checking a condition and includes a { block } of code to run as long as the condition remains true.  When the condition becomes false, the loop stops iterating and execution continues with the next line of code after the { block }.  Because the condition is so important to the while loop, it is commonly called a conditional loop in Computer Science.

Here’s the same program using a while loop and a variable for the x-coordinate:

On line 13, after the keyword while, is a condition.  If that condition is true, the { block } of code following it runs one time.  Execution then returns to line 13, and the condition is checked again.  This process continues until the condition finally becomes false (i.e., when x becomes greater than 300).  Can you see how this is like a repeating if statement?

If you try resizing the canvas width, you’ll find that there are either too many lines or too few lines drawn to make a balanced pattern.  For even greater flexibility, we can adjust the condition like so:

while (x <= width-100) {

This way the loop will draw as many lines as needed based on the width system variable.

Technically, that’s all there is to know about how a while loop works, the rest is practice!

Logic Errors

We know that that a syntax error is essentially a typing mistake (misspelt keyword or incorrect symbol) in our code.  But there is another kind of error called a logic error that can be a lot harder to find/fix especially when dealing with loops.  A logic error occurs when the syntax of some code is correct, but when you run it you get unexpected results.  For example, maybe you’ve used the wrong operation in a calculation and got an incorrect result.

Warning: Before you try the next program make sure you have saved any important work.

Have a look at this code, but do not run it (yet):

Can you spot the problem?  On line 12 we are subtracting 1 from x, meaning that x will become a negative number and the condition of the while loop will never become false.

If you try running this program you will see that it hangs the p5.js editor in what is called an infinite loop.  An infinite loop is a particular kind of logic error where the loop will never stop because its condition will never become false.  Watch out for these kinds of errors!

You Try!

  1. Draw a series of horizontal lines from the top to the bottom of the canvas.  I’ve used a spacing of 20 pixels here.  Make your code flexible so that it will automatically work with any canvas size.
  2. Draw a series of concentric circles to fill the canvas. Darken each circle as you move toward the center.  You will need 2 variables here, one for circle diameter, and one for greyscale darkness.