5.1- While Loop

Iteration!

Computers are programmed to do tasks over and over again. When we find ourselves drawing the same shape repeatedly, the computer should be doing all that hard work for us. We just have to tell it how.

The WHILE loop requires three steps

  • An initial condition
  • A while loop that stops at some point based on a boolean question
  • A loop operation

(Learning Processing, Chapter 6)

Example: Multiple Lines

Start with a sketch that draws a bunch of lines that have the same length and are spaced 10 pixels apart:

void setup(){
size(200,200);
background(255);
}

void draw(){
stroke(0);
line(50,60,50,80);
line(60,60,60,80);
line(70,60,70,80);
line(80,60,80,80);
line(90,60,90,80);
line(100,60,100,80);
line(110,60,110,80);
line(120,60,120,80);
line(130,60,130,80);
line(140,60,140,80);
line(150,60,150,80);
}

Now draw the same lines with variables

int len = 20;
int x = 50;
int y = 60;
int spacing = 10;

void setup() {
  size(600, 600);
  background(255);
}

void draw() {
  x = 50; //why do we reset x to 50???
  line(x, y, x, y+len); 
  x = x+spacing;
  line(x, y, x, y+len);
  x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len);
   x = x+spacing;
  line(x, y, x, y+len); 
  x = x+spacing;
  line(x, y, x, y+len);
}

Now that we see the repition, we can use a WHILE loop to draw as many legs as we want!

int w =30;
int x = 50;
int y = 60;
int len = 80;
int spacing = 10;
int endLegs = 550;

void setup() {
  size(600, 600);
}

void draw() {
  background(255);
  fill(255, 0, 0);
  x = 50;
  while (x < endLegs) {
    line(x, y, x, y+len);
    x = x + spacing;
    println(x);
  }
}

Change the spacing variable to change how many legs there are!

Beware of infinite loops! Your boolean expression HAS to become false at some point, otherwise you will freeze your program and need to restart Processing.

Print this page

Leave a Reply

Your email address will not be published. Required fields are marked *