Arrays

Arrays
Simple yet powerful tool (or data structure).

Once you see yourself write something like i1, i2, i3...

...it might be time to use an array.

It turns then i[0], i[1], i[2]

and you can easily tackle it with for-loops and have hundreds of is... or flowers... or cars... or ballons...

The trick is to leave the array as it is and just change the index n when the mouse is pressed or whatever.

The array is a list. Each line of the list has one value. All values are of the same type. You use one value by saying give me in the list with name listMy the value of line 3. This is written as listMy[3] - so it's with [ and ] for the line number.

Btw. all arrays start with 0 so the first element is in line 0, the 2nd in line 1 etc.; to retrieve the 3 element say listMy[2].

Without Arrays:
int p1 = 250; int p2 = 50; int p3 = 450; void setup {   size( 800, 800); fill(255, 2, 2); } // setup void draw {   background(255); ellipse(p1, 100, 12, 12); ellipse(p2, 100, 12, 12); ellipse(p3, 100, 12, 12); } // draw

With arrays:
int[] p = { 250, 50, 450 };  void setup {   size( 800, 800); fill(255, 2, 2); } // setup void draw {   background(255); for (int i = 0; i < p.length; i++) { ellipse(p[i], 100, 12, 12); } } // draw but now we can do all sorts of things.

Without the code getting real long, we can have 100 ellipses.

100 Ellipses
Without the code getting real long, we can have 100 ellipses.

// make an empty array with 100 slots int[] p = new int [100]; void setup {   size( 800, 800); for (int i = 0; i < p.length; i++) { p[i] = int(random(0, width)); }   fill(255, 2, 2); } // setup void draw {   background(255); for (int i = 0; i < p.length; i++) { ellipse(p[i], 100, 12, 12); } } // draw

Parallel Arrays:
Now we want each ellipse to have also a different y position and color. We use three parallel arrays for this:

// make an empty array with 100 slots int[] pX = new int [100]; int[] pY = new int [100]; color[] pColor = new color [100]; void setup {   size( 800, 800); for (int i = 0; i < pX.length; i++) { pX[i] = int(random(0, width)); pY[i] = int(random(0, width)); pColor[i] = color (random(255), random(255), random(255)); } } // setup void draw {   background(255); for (int i = 0; i < pX.length; i++) { fill(pColor[i]); ellipse(pX[i], pY[i], 12, 12); } } // draw

Fun!