Loops

Image result for loop

So how boring would it be if you were playing Pac-Man and when you lose, that was it, you couldn’t get a second chance? Well the concept of looping is one of the most powerful concepts at a programmer’s finger tips.

There are two main different types of loops (There are others),

For Loops and While Loops.

For Loops have a structure that look like this… i++ is shorthand for i = i + 1

So this is the notation for a for loop, we have a variable i that starts at 0, then we check is that variable less than 50(can be any number or variable), and then increment the variable

So we can use this to repeat code without writing out multiple lines. It also has the power to be a tool to do an incremental process.

Let’s say we want to create 50 circles in p5. Instead of writing this,

This is just miserable to look at…

we can write this, which as lot more modular.

much more readable and manageable

You can also use a For Loop inside of another For Loop. This is called a nested For Loop. So you will have to break it down to know exactly what is happening but here is an example.

Image result for nested for loop javascript

This will go through the first loop, then do the second loop as many times as that it is defined. Then it will jump back up to the first loop, increment, and repeat the process.

Similar idea but a While Loop can be used until a condition is true, instead of just checking against a number comparison.

While loop

Here’s an example of a while loop. While the condition in the parentheses is true the code in the loop will execute. In this example we are using a boolean variable that p5 will change to false or true depending on if the mouseIsPressed, it would be a good idea to make sure that the condition can be changed somewhere in the loop, or else it could go on infinitely which would be a big problem. It helps to think about what will happen logically before you start testing a program with a while loop!

I would highly recommend Dan Shiffman’s channel, The Coding Train, linked here. It’s a great resource and explains concepts like this in a fun and easy way.

Leave a comment