Osion kuvaus

  • 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 members 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. See here for an example: arrayloop.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++)

    Homework

    Make an array that holds the following data set consisting of consecutive x and y coordinates and colors:

    100,100,#ff0000, 500,200,#00ff00, 300,500,#0000ff, 200,400,#808080

    Plot it from the array using a loop. The outcome should look like this:

    Plot

    Ver solución: dataplot.pde