Arrays

An array is a list, a collection of data. More precisely, is an ordered arrangement of homogenous data.

 

(If a variable is a drawer to put values in, an array is a drawer chest of numbered drawers, each of which can hold a piece of data for you)

 

Homogenous means that an array holds together data of the SAME datatype: you can have an array of integers, or an array of characters, or an array of colors but you can not have an array of mixed types.

Ordered means that every element (every piece of data in the array) has a place, a position in the array. So, if you want to access an element in an array, you need to know its position (index)

array1d

*The first place in an array is always at index (position) 0 (I told you so, programmers like to count from 0 instead from 1!)

How to declare an array

To create an array, you need to specify what kind of data this array is going to store (its datatype, can be any of the datatype you already know) and how many elements it can store (its length)

 

int[] my_array=new int[5]; //this is an array of 5 integers boolean[] another_array=new boolean[10]// this is an array of 10 boolean variables color[] square_colors= new color[100];

How to access an array element

int[] my_array=new int[5];

 

my_array[0] //this is the 1st element or the array my_array at position 0

my_array[1] //this the 2nd element at position 1

my_array[2] //this is the 3rd element at position 2

my_array[3] //this is the 4th element at position 3

my_array[4] //this is the last (5th) element at position 4

 

* You last position (index) is always one less than your length (remember, we count from 0!)

* NEVER ask for an index that is greater than you last position

 

Array elements are just data at the end, so you can use them exactly as your normal variables.

e.g. since my_array is an array of integers, my_array[0] will be an integer at the end

int sum;
sum= my_array[0]+10;

Hey, wait a second! Your array is still empty!

True! Just like normal variables, you need to assign values to your array elements before using them.

 

You can do that one by one e.g.

my_array[0]=10;
my_array[1]=20;

 

or you can give initial values when you create (declare) an array

 

int[] my_array={10,20,30,40,50}; //note that you don't need the new keyword now color[] fancy_colors_to_use= {color(255,0,0), color(255,255,0),color(0,0,255)};
//useful when you want to use preselected colors
String[] names = { "Prospero", "Miranda", "Ariel" ,"Caliban", "Alonso"};
//some predefined names to use

 

But you don't really want to do any of the above for a large amount of elements. And here is where LOOPS come in to make you life much much easier!