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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Figure 6-9. Multiple r<strong>and</strong>omized particle lines<br />

I imagine some of you might need a little clarification on parts of this last example.<br />

Although this is a simple program in number of code lines, parts of it are a bit dense.<br />

When you nest a for loop, as in the example, it is important to underst<strong>and</strong> how the loop<br />

executes. The outer for loop initializes i to height/totalRows. This loop will run as long<br />

as i is less than the height of the display window. i will be incremented by the same<br />

amount i is originally initialized to, height/totalRows. On the first iteration of the outer<br />

for loop, the inner for loop runs through an entire loop cycle. In this case, j is initialized<br />

to 1 <strong>and</strong> also incremented by 1 as long as it remains less than the value of steps. After the<br />

inner loops runs through all its iterations, control goes back to the outer loop, which is<br />

incremented by height/totalRows; <strong>and</strong> then the process repeats itself, with the inner<br />

loop again going through its entire iterative loop cycle. This process will continue until the<br />

condition in the outer loop no longer evaluates to true (i is no longer less than the height<br />

of the display window). As you might imagine, if you’re not careful, you can pretty easily<br />

create nested loops that take a lot of time to finish.<br />

One other significant point regards how you name your variables in the loops. Within a<br />

code structure bounded by curly braces (for loops, if statements, functions, etc.), variables<br />

declared in the head or body of the structure (or passed in, as in the case of parameters<br />

in the head of a function) have local scope. This is in contrast to variables declared<br />

at the top of a program, which have global scope. Because of local scope, the variable i,<br />

declared in the head of the for loop, only exists between the curly braces of the for loop;<br />

it has no existence outside the loop. That’s why it’s possible to use the same-named<br />

LINES<br />

183<br />

6

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

Saved successfully!

Ooh no, something went wrong!