Arrays

About Arrays

Using Arrays

An Example

This example uses an array to store sizes for a set of ellipses.
int[] sizes; void setup() { size(800,600); sizes = new int[5]; sizes[0] = 10; sizes[1] = 45; sizes[2] = 5; sizes[3] = 80; sizes[4] = 120; } void draw() { background(255); fill(0,0,255); ellipse(100,300,sizes[0],sizes[0]); ellipse(200,300,sizes[1],sizes[1]); ellipse(300,300,sizes[2],sizes[2]); ellipse(400,300,sizes[3],sizes[3]); ellipse(500,300,sizes[4],sizes[4]); }
This doesn't seem to useful - it's a lot of work for something we could do in a much easier way without all this fooling around with ellipses. But, we can make it a little more efficient by using a for loop to automatically draw all the ellipses instead of having to draw them each one by one. And, we can make the initialization easier by storing all the numbers in the array at once.
// initialize the array all at once int[] sizes= { 10,45,5,80, 120}; void setup() { size(800,600); } void draw() { int i; // index variable for the loop int x; // x-coordinate of any individual dot background(255); fill(0,0,255); for (i=0;i < 5; i++) { x = 100 + (i * 100); // x will be 100,200,300, etc. ellipse(x,300,sizes[i],sizes[i]); // sizes[i] is the size of dot number 'i' } }