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.

PROCESSING: CREATIVE CODING AND COMPUTATIONAL ART<br />

88<br />

variables have global scope, meaning that they can be seen from anywhere within your<br />

program, including within loops. In the earlier while loop example, the variable x has<br />

global scope <strong>and</strong> can be seen anywhere in the program:<br />

int x = 1000;<br />

while (x>=0) {<br />

println (x);<br />

x -= 100;<br />

}<br />

Thus, you would not want to use x again as a counter in another loop later in the same<br />

program, as it could cause unpredictable results. Because the for loop solves this problem<br />

by keeping the counter variable local in scope, I tend to use for loops far more often than<br />

while loops.<br />

In the next section, “Functions,” I’ll go more into detail on local vs. global scope. Here are<br />

a couple of other examples of for loops:<br />

for (int i=1000; i>50; i-=2)<br />

println(i);<br />

}<br />

for (int i=1000, j=200; i>50; i-=2, j++)<br />

print("i = ");<br />

println(i);<br />

print("j = ");<br />

println(j);<br />

}<br />

The top example is just a variation on the for loop discussed previously. It just counts<br />

down by two instead of counting up by one. The second loop example uses multiple variables<br />

<strong>and</strong> incrementors in the head—which is legal. You just separate the different<br />

variables with commas. Try running this last loop example to view the output; it will help<br />

you underst<strong>and</strong> how the for loop runs.<br />

for loops can add tons of efficiency to your code, <strong>and</strong> used cleverly can really cut down<br />

on the number of code lines. As an example, I’ve recoded the stepped radial gradient (see<br />

Figure 3-4) using a for loop, converting it into a smoother continuous gradient.<br />

//Continuous radial gradient<br />

size(200,200);<br />

background(0);<br />

for (int i=255; i>0; i--){<br />

noStroke();<br />

fill(255-i);<br />

ellipse(width/2, height/2, i, i);<br />

}

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

Saved successfully!

Ooh no, something went wrong!