Arrays
About Arrays
- Arrays are variables that can store multiple bits of data - a list of numbers, a list of text strings, a list of points, a list of images.
- Use an array whenever you need to keep track of a whole group of related data. The
- Storing data in an array lets you use a loop to automatically process all the items in the array
Using Arrays
- Declaring:
int [] myArray;
The square brackets after the variable type mean that this variable is an array of integers, not just one integer. - Initializing:
myArray = new int[100];
You have to initialize the array, telling Processing how big it actually is. This array can store 100 integers. - When you choose a size for the array, you can't go over it - trying to store more than 100 numbers will cause an error.
- Storing Data: use the square brackets to choose which array element you want to use.
Note that 0 is the first element, not 1.myArray[0] = 545; myArray[1] = 432; myArray[2] = 78345; - Using Data: again, just use the square brackets:
println(myArray[0]); println(myArray[1]); myArray[2] = myArray[0] + myArray[1]; println(myArray[2]);
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'
}
}