Skip to content

Repetition in Programs: the while-loop#

Computers are great at automation and repetition. They create simulations with millions of particles. They transfer billions of bytes without errors. They draw millions of pixels to your screen. Right now. Sixty times per second (or more!).

So far, we haven't looked at repetition much. All these things above would not be possible without repetition. If you've been playing "Human Resource Machine", repetition is part of the very first levels already. It is quite literally the second thing that game makes you do!

Human Resource Machine Level 2

Human Resource Machine Level 2

If you have not already, play Human Resource Machine up to level 2.

In that particular case, the solution is that newfangled "jump" instruction. What you are doing, is creating an endless loop. If the game didn't automatically end the level, that employee would run around that mail room forever!

In programming we normally create loops that run for a limited amount of time (although creating endless loops is a fun1 source of errors).

Human Resource Machine Level 19

You will get to that point by Level 19 ("Countdown") in Human Resource Machine. It asks you to take a number from the INBOX and count down to zero.

Human Resource Machine Level 19

It's the FinalFirst Countdown#

Flowchart of a countdown

How would we count down to zero in our Processing code instead? In Human Resource Machine, we check for some condition. And this is exactly what we must do in Processing as well:

int counter = 10;
while (counter >= 0) {
    println(counter);
    counter = counter - 1;
}
println("liftoff");

There's a new keyword in this piece of code, and it's called while. while looks a lot like if in this piece of code and our flowchart would totally agree! while also checks for some condition in its parentheses. And depending on its check it either runs its code block, or skips over it. The difference is, that while will keep doing that over and over again until the condition is no longer met.

In our countdown, we start at the initial value 10. 10 is clearly >= 0 - so this will be true✅ and our code block gets executed. In the code block, we subtract from our counter. So on the next run, it is 9, which is still >= 0. Rinse. Repeat.

At some point, our counter will be 1, still larger than or equal to zero. Then it will be 0still at least equal to zero. The condition is still met. We're still printing that 0. We're subtracting one more. We now have -1 in our counter. We go back to our while in line 2. While checks if -1 >= 0 and that clearly is false❌. Now we no longer run our code block and break out of that loop. We can finally continue with the rest of the code.

Our output will look like this:

10
9
8
7
6
5
4
3
2
1
0
liftoff

A Counter, A Check and a Change walk into a Loop

This is a really common setup for a jokeloop. The vast majority of the loops you will see or write will have some kind of counter. That counter will be compared to something. And you will change that counter.

Beware of the Endless Loop#

As mentioned earlier, it is very easy to create an endless loop. Look at this example:

int counter = 10;
while (counter >= 0) {
    println(counter);
}
println("liftoff");

Spot the Difference

Can you spot the difference? What would be its output? More importantly, when would that rocket reach liftoff?

Hint (you might need to reload this page if you dare to open this) This would produce an eternal torrent of 10s. This is just a very slow excerpt. Right now, this box contains 0 lines.

Repeated Drawing#

As in all other cases so far, you can put whatever you want into the code block of a while-loop! Let's draw something:

10 white circles

int counter = 0;
size(200, 200);
background(40, 30, 90);
textSize(16);
textAlign(CENTER);
while (counter < 10) {
    circle(counter * 10, 50, 8);
    text(counter, counter * 10, 43);
    counter = counter + 1;
}

Nothing special here, just ten circles and ten numbers.

Programmers love their 0

Loops, by the way, are one of the things where programmers like to count from zero. If you need ten of something, the most common way by far will be to count from 0 to < 10, like we're doing in the example above.

Counting from 1 to <= 10 would give you almost the same result - it would also give you 10 numbers, but instead of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 it would give you the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. In many cases, it's easier to work with the first set of numbers.

Breaking Out of a Loop#

There are various ways of breaking out of a loop. The counter is just the most common one. Anything that can be a condition can control your while loop:

Any Condition 1#

Here, we're using some pixel value to break out of that loop:

int spacing = 15;

void setup() {
    size(120, 300);
}

void draw() {
    background(40, 30, 90);

    int yPosition = 0;
    while (yPosition < mouseY) {
        rect(10, yPosition, 100, 12);
        yPosition = yPosition + spacing;
    }
}

Any Condition 2#

Here, we're using a more complicated construct to determine how long this loop should run:

float rotationalSpacing = 0.2;

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

void draw() {
    background(40, 30, 90);
    translate(100, 100);

    int strips = floor(random(0,16));
    while (mousePressed && strips > 0) {
        strips--;
        rect(-90, -5, 40, 10);
        rotate(rotationalSpacing);
    }
}

This will draw an arc of white rectangles, but only as long as any mouse button is pressed.

Drawn arc just as long as the mouse is pressed

shorthands for increment and decrement

In loops, the shorthands to increment and decrement a number are used very often. Please make sure to check the section about these short forms ++ and -- if you're unfamiliar with syntax like strips-- in line 13!

Output Numbers

Combine a loop and println() to print the numbers from 0 to 99 to the text output window.

Relevant excerpt from Learning Processing#

(the section starts at 2:50:01 and runs through 2:57:48, the video should start and stop on these automatically.)


  1. Not fun at all.