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.

88 <strong>Learning</strong> processing<br />

Looking at the above examples, we can see that a for loop consists of three parts:<br />

• Initialization —Here, a variable is declared and initialized for use within the body of the loop. This<br />

variable is most often used inside the loop as a counter.<br />

• Boolean Test —This is exactly the same as the boolean tests found in conditional statements and<br />

while loops. It can be any expression that evaluates <strong>to</strong> true or false.<br />

• Iteration Expression —The last element is an instruction that you want <strong>to</strong> happen with each loop<br />

cycle. Note that the instruction is executed at the end of each cycle through the loop. (You can have<br />

multiple iteration expressions, as well as variable initializations, but for the sake of simplicity we will<br />

not worry about this now.)<br />

START<br />

WITH THIS<br />

for (int i = 0; i < 10; i+ +) {<br />

3 RUN THE CODE<br />

}<br />

fi g. 6.7<br />

Increment/Decrement Opera<strong>to</strong>rs<br />

1<br />

4<br />

5<br />

DO THIS<br />

RETURN TO #2<br />

2<br />

TEST THIS<br />

IF FALSE EXIT<br />

#4 & #5 ARE “INVISIBLE”<br />

In English, the above code means: repeat this code 10 times. Or <strong>to</strong> put it even more simply: count from<br />

zero <strong>to</strong> nine!<br />

To the machine, it means the following:<br />

• Declare a variable i,<br />

and set its initial value <strong>to</strong> 0.<br />

• While i is less than 10, repeat this code.<br />

• At the end of each iteration, add one <strong>to</strong> i .<br />

Th e shortcut for adding or subtracting one from a variable is as follows:<br />

x ++; is equivalent <strong>to</strong>: x � x � 1; meaning: “ increment x by 1 ” or<br />

“ add 1 <strong>to</strong> the current value of x ”<br />

x � � ; is equivalent <strong>to</strong>: x � x � 1;<br />

We also have:<br />

x � � 2; same as x � x � 2;<br />

x * � 3; same as x � x * 3;<br />

and so on.<br />

A for loop can have its own variable just for the<br />

purpose of counting. A variable not declared at<br />

the <strong>to</strong>p of the code is called a local variable.<br />

We will explain and defi ne it shortly.

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

Saved successfully!

Ooh no, something went wrong!