04.04.2013 Views

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

PROCESSING: CREATIVE CODING AND COMPUTATIONAL ART<br />

86<br />

while is a reserved keyword in <strong>Processing</strong>, like the keywords if <strong>and</strong> else, which you’ve<br />

already looked at. A while loop will execute the code between its open <strong>and</strong> closed curly<br />

braces as long as the condition between the parentheses is true. In the example, the condition<br />

will always be true. true is actually another reserved keyword in <strong>Processing</strong> <strong>and</strong> Java<br />

that always means, well . . . true. Can you see why I didn’t want you to run this loop example?<br />

It will never stop running, as there is no exit condition (i.e., a condition that when<br />

reached will cause the code to continue past the loop). Nasty loops like this are called<br />

infinite loops, <strong>and</strong> they are to be avoided. Of course, you can force the <strong>Processing</strong> application<br />

to quit, so don’t panic if you did try running it (against my sage advice). Here’s an<br />

improved <strong>and</strong> safe version of that last demonic loop:<br />

int x = 0;<br />

while (x=0) {<br />

println (x);<br />

x -= 100;<br />

}<br />

This loop outputs the values 1000 through 0, decrementing by 100 each cycle, or iteration,<br />

of the loop. Also, I set the condition using >=, so 0 was output as well.<br />

do . . . while<br />

A while loop will only execute if the condition is true. However, there are times when<br />

you’ll want a loop to execute at least once no matter what. The do...while loop is sort of<br />

a backward while loop that always executes at least once, regardless of whether the condition<br />

is true. After the first iteration of the loop, though, it behaves just like a regular<br />

while loop. Here are two examples:<br />

//example 1.<br />

int x = 50;<br />

do {<br />

println(x);<br />

x += 1;<br />

}<br />

while(x

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!