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

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";

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

This entry was posted in Processing. Bookmark the permalink.