4. Arrays, loops, types, random

Arrays (taulukot)

So far we’ve used variables, which let you store single values and work with them. Often we need to process large amounts of data, and single variables aren’t enough for that. Arrays let you store multiple values of similar type. Like variables, arrays too have: a name, a type, value(s), and a scope. In addition to that they have size, which is the amount of member in the array. So, if a variable is a box, an array would be a pile of those boxes.

An array can be declared the following way:

int ourstuff[] = {2,4,6,7,8};

After this line ourstuff is at our disposal and contains five numbers. It’s possible to create arrays also without assigning any values, only specifying their size. An array with 100 members:

int ourstuff[] = new int[100];

Array members (also known as items) can be used exactly like variables, through referencing (viittaus):

ourstuff[1]=2;
ellipse(ourstuff[1],ourstuff[2], 10,10);

The number inside the brackets is known as index. The first index in C-like languages such as Java and Processing is zero. So, for ourstuff the indices are in the range 0..4

Arrays and loops

In general, arrays go together with loops, especially for loops. With a loop you can walk through all the members of the array when needed. The loop counter is used as the index. Two examples: arrayloop.pde and circlesfromarrays.pde

Often we don’t know the size of the array beforehand, or its size might change. A safe way to go through all the items is to use the length property that all arrays have:

for(i=0; i<ourstuff.length; i++)

Strings (merkkijonot)

A new type coming up. Type int lets us use integer numbers, but there’s many situations when other types are needed. Textual information can be stored in type String. You declare a string as any other variable.

String mytext;

Assignment is the same. A string is enclosed in double quotes:

mytext="Never gonna give you up";
println(mytext);

You can’t directly assign variables of one type to another type. You need type conversion.

Debugging exercise

Download the following sketch: mousefollowbuggy.pde and fix it! There are ten errors altogether: some of them just minor typos and some more conceptual problems. Here’s the fixed one: mousefollowfixed.pde

Random numbers (satunnaisluvut)

Random numbers are essential for many purposes, for example games where enemies appear at random positions at random intervals. They can be generated using the random function. A random number from 0 to 100 (excluding number 100) is generated by random(100):

line(random(100),random(100), random(100),random(100));

A larger example

Let’s combine most of the things we’ve learned so far. A sketch that draws squares that can be removed with a mouse click: clicktokill.pde

Posted in Processing | Leave a comment

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()

Posted in Processing | Leave a comment

2. Variables (2), math, interaction

Recap of variables. Properties, declaration, assignment. Conflict with reserved words.

Simple mathematics in Processing

We can use variables for many kinds of calculations, such as addition (+), division (/), subtraction (-) and multiplication (*). In the mathematical statements we can use variables as well as numbers:

a=1+2;
a=b*2;
a=a+1;
a=b/3+a*3-40+c*b;

Optionally you can insert spaces to make it a bit more readable:

a = b/3 + a*3 -40 + c*b;

To see the number (will appear in the black box of the processing window) use print or println: println(a);

I’d rather not talk about these for now, but in a lot of tutorials and examples you will find things like this:

a++;
b––;

They’re only shorthand for a=a+1; and b=b-1; Use them only when you need to increment or decrement a variable by one, not in mathematic statements.

Interactive software

So far we’ve only made small sketches that are run once. For most uses we need to have the sketch running continuously. For this we need two things: setup (run once when the sketch starts) and draw (runs all the time). Things that you need once, like opening the window go under setup, things that are done continuously go under draw. This is a bit different to many other environments. An example program with setup and draw: setupdraw.pde

Comments (kommentit)

For the sake of clarity it’s essential to use comments. They serve both you and others reading your code. Comments are free-form and start with two slashes: // The rest of the line is ignored. Edit – Comment/Uncomment will do it automatically for you. Another use for comments is disabling a piece of code for testing purposes. comments.pde

Using the mouse

There are global variables named mouseX, mouseY, mousePressed and mouseButton, which you can use for simple interaction. Their values are updated automatically and they don’t need to be declared (they’re declared somewhere else). Their values can be used normally:

ellipse(mouseX, mouseY, 100,100);

An example doing something almost useful with a mouse: mousepaint.pde

Variable scope (näkyvyys)

Global variables, Local variables. Global variables are visible to all parts of the sketch. As a rule of thumb: the scope is the block enclosed in braces { }. Declaration must be done before use, too. Why are global variables bad? Different variable scopes in this example: variablescopes.pde

Posted in Processing | Leave a comment

1. Introduction, graphics, variables

Course structure, aims, assessment. A brief history and overview of programming languages (slides). Walkthrough of the Processing user interface.

Special characters

… and how to type them on a Finnish Mac keyboard. We’ll need many of these when typing in our programs, since they have special meanings. Finnish translations for the non-obvious ones included:

  • parentheses ( )
  • square brackets (hakasulut) [ ] – alt-8, alt-9
  • braces/curly brackets (aaltosulut) { } – alt-shift-8, alt-shift-9
  • asterisk *
  • slash (kauttaviiva) /
  • pipe (putki) | – alt-7
  • ampersand &
  • equal sign, “is” =
  • colon :
  • semicolon ;
  • comma ,
  • hash (“risuaita”) #
  • tilde (“mato”) ~ – alt-^-space
  • single quote (heittomerkki) – note that this is not the same as accent ´
  • double quote (lainausmerkki)
  • less/greater than < >

Program flow

Statements are executed (“run”) sequentially line by line. The order of the statements is crucial: changing it will result in completely different end results. Comparable to a cake recipe: there’s ingredients (data) and instructions what to do (program code, statements).

Basic graphics with Processing

size, background, point, ellipse, rect, fill etc. See the Processing reference for a complete list of graphical primitives supported by the language – there’s a lot at your disposal. An example sketch: simplegraphics.pde

Variables (muuttujat)

We could consider variables “boxes”, where you can store things. During the following lectures they will be used for several purposes such as counters, for holding status information such as mouse coordinates and for making the code more readable. In Processing every variable has a type, a name, a value and a scope. Before we can use a variable we need to declare (esitellä) it, which looks like this:

int whatever;

The type in this case is int, an integer number (kokonaisluku). The name we can choose freely, except that it can’t overlap with reserved words of the language. The value is set through assignment (sijoitus):

whatever=100;

Finally, the scope is the area where a variable is visible. It can be global (yleinen) or local (paikallinen). More about that later. An example with a variable declaration and use: onevariable.pde

Posted in Processing | Leave a comment

Starting up again

Yet another round of Software Studies for Media Designers is about to begin. These pages will be updated throughout the course with examples, lecture material and so on. For now, you can check the MyCourses page for information on the schedule.

The course consists of two parts. First, there will be six mornings of programming basics with Markku Reunanen and Processing (if you wish to use your own computer, the tool can be downloaded for free from the website). The second half will be taught by Suse Miessner in JavaScript.

Welcome onboard, and as we like to put it: Programming is for everyone!

Posted in Uncategorized | Leave a comment