3. Flow control

Flow control

In numerous cases we need to do things conditionally, a number of times, or until something happens. For those sort of purposes we have different flow control statements:

  • if – do something if a condition is true
  • if-else – do something if a condition is true, otherwise do something else. See ifelse.pde
  • for – repeat something a certain number of times. Consists of the initial counter value, condition and increment. See forloop.pde
  • while – repeat something as long as a condition is true. Quite rare in Processing because of the way interactive sketches work, but common in other languages and environments.

These statements start a compound statement, which is a block of code enclosed in braces. Anything you put in there will be run or repeated, according to the statements above. You can also nest the compound statements, placing them inside each other. Nesting example: nestedloops.pde

Comparison operators (vertailuoperaattorit)

All of the above need conditionals. Comparison operators are used for comparing two things, such as numbers or variables. Some of the most common ones we’ll use in the future are:

  • Equal: == (very easy to mix up with assignment, beware!)
  • Not equal: !=
  • Greater than: >
  • Less than: <

Grouping conditionals

Conditionals can be grouped, if you want to do more comparisons in the same time:

  • And: &&
  • Or: ||

For example: if(mouseX>100 && mouseX<200). A complete example: exitbutton.pde

Indentation (sisennys)

It’s a good common practice to indent the contents of compound statements a few characters to the right, so that they are visually aligned. This way you can instantly spot the statements that are on the same level. Processing will do most of it for you automatically, but if your code has gotten ugly, you can clean it up by selecting it and then clicking Tools – Auto Format.

One more nitty detail: to quit your sketch use command exit()

This entry was posted in Processing. Bookmark the permalink.