06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

218 <strong>Learning</strong> <strong>Processing</strong><br />

Th e defi nition of fac<strong>to</strong>rial includes fac<strong>to</strong>rial ?! It is kind of like saying “ tired ” is defi ned as “ the feeling you<br />

get when you are tired. ” Th is concept of self-reference in functions is known as recursion . And we can use<br />

recursion <strong>to</strong> write a function for fac<strong>to</strong>rial that calls itself.<br />

int fac<strong>to</strong>rial(int n) {<br />

if (n == 1) {<br />

return 1;<br />

} else {<br />

return n * fac<strong>to</strong>rial(n-1);<br />

}<br />

}<br />

Crazy, I know. But it works. Figure 13.15 walks through the steps that happen when fac<strong>to</strong>rial(4) is called.<br />

becomes 24<br />

fac<strong>to</strong>rial(4)<br />

fi g. 13.15<br />

becomes 6<br />

return 4 * fac<strong>to</strong>rial(3)<br />

return 3 * fac<strong>to</strong>rial(2)<br />

Th e same principle can be applied <strong>to</strong> graphics with interesting results. Take a look at the following<br />

recursive function. Th e results are shown in Figure 13.16 .<br />

void drawCircle(int x, int y, float radius) {<br />

ellipse(x, y, radius, radius);<br />

if(radius > 2) {<br />

radius * = 0.75f;<br />

drawCircle(x, y, radius);<br />

}<br />

}<br />

becomes 2<br />

becomes 1<br />

return 2 * fac<strong>to</strong>rial(1)<br />

return 1<br />

fi g. 13.16<br />

What does drawCircle( ) do? It draws an ellipse based on a set of parameters received as arguments, and<br />

then calls itself with the same parameters (adjusting them slightly). Th e result is a series of circles each<br />

drawn inside the previous circle.<br />

Notice that the above function only recursively calls itself if the radius is greater than two. Th is is a crucial<br />

point. All recursive functions must have an exit condition! Th is is identical <strong>to</strong> iteration. In Chapter 6, we<br />

learned that all for and while loops must include a boolean test that eventually evaluates <strong>to</strong> false, thus<br />

exiting the loop. Without one, the program would crash, caught inside an infi nite loop. Th e same can be

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

Saved successfully!

Ooh no, something went wrong!