Loops

Assumed Knowledge
Learning Outcomes
  • Know the two types of loops
  • Understand how to use loops to draw multiple things in one frame
  • Understand syntax and semantics of loops
  • Be able to trace loops with tables

Loops

Loops are similar to conditions except that after every iteration of the loop, the expression is checked again.

Chapter 6 of Learning Processing by Danel Shiffman.

Statement or Expression

Firstly, loops are statements not expressions, for the same reasons as if statements. That means they don’t have an equivalent value. Instead, they are useful because of what they do.

Both loops and if statements are called “control-flow” statements because they change the flow of the program from top-to-bottom to somethings more complex. We will see another control flow statement when we see functions.

Modify your animated blue circle so that it is an animated blue bullseye instead. Hint: You can get a thin circle using noFill and a larger strokeWeight value;

solution

Instead of drawing a simple circle, we draw three circles, each 10 pixels larger than the last. Each has a 2 pixel border, making a bulleye shape. Nothing else needs to change, the center of the bullsye animates in exactly the same way as the circle did.

int ypos;
int speed;

void setup(){
  ypos = 0;
  speed = 1;
}

void draw(){
  background(255);
  
  if (ypos == height){
    speed = -1;
  }
  if (ypos == 0){
    speed = 1;
  }
  noFill();
  stroke(92, 136, 218);
  strokeWeight(2);
  for(int i = 0; i < 40; i = i + 10){
    circle(width/2, ypos, i);
  }
  ypos = ypos + speed;
  
}

Looking at loops without the draw loop

As discussed in the above video, the fact that processing is always in a “draw loop” can confuse things somewhat. It is possible to see all the operation of loops free of this constraint if we work only on the console. The console is the black area below your program and it is available even when you do a “static” processing program (one that has no setup or draw).

Using loops, draw five ^ (hat) characters to the console

solution
for(int i = 0; i < 5; i++){
	print('^');
}

Notice that this program has no setup and no draw functions, it is a special type of non-animated Processing program.

Nesting of control structures

Control structures are literally like lego blocks, you can arrange them as you want, depending on the situation. So you can put loops/conditions inside other loops/conditions (and then more loops/conditions inside that and so on).